返回

使用 JavaScript 学习数据结构:队列与链表

前端




## **队列与链表**  ##

队列和链表都是数据结构,它们都用来存储数据,但它们之间也有着一些关键的区别。

**队列** 是一种先进先出 (FIFO) 的数据结构,这意味着第一个进入队列的数据项也是第一个离开队列的数据项。队列通常用数组或链表来实现。

**链表** 是一种线性的数据结构,其中的元素以链式的方式连接起来。链表中的每个元素都包含两个字段:一个指向下一个元素的指针和一个存储数据项的字段。链表通常用对象或类来实现。

## **队列的实现**  ##

队列可以使用数组或链表来实现。使用数组实现队列比较简单,只需要一个数组和两个指针来跟踪队列的头部和尾部。

```javascript
class Queue {
  constructor() {
    this.items = [];
    this.head = 0;
    this.tail = 0;
  }

  enqueue(item) {
    this.items[this.tail] = item;
    this.tail++;
  }

  dequeue() {
    if (this.isEmpty()) {
      return null;
    }
    const item = this.items[this.head];
    this.head++;
    return item;
  }

  peek() {
    if (this.isEmpty()) {
      return null;
    }
    return this.items[this.head];
  }

  isEmpty() {
    return this.head === this.tail;
  }

  size() {
    return this.tail - this.head;
  }
}

链表的实现

链表可以使用对象或类来实现。使用对象实现链表比较简单,只需要一个对象来存储数据项和一个指针来指向下一个元素。

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  append(data) {
    const newNode = new Node(data);
    if (this.isEmpty()) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }
  }

  remove(data) {
    let current = this.head;
    let previous = null;
    while (current !== null) {
      if (current.data === data) {
        if (previous === null) {
          this.head = current.next;
        } else {
          previous.next = current.next;
        }
        if (current === this.tail) {
          this.tail = previous;
        }
        return true;
      }
      previous = current;
      current = current.next;
    }
    return false;
  }

  find(data) {
    let current = this.head;
    while (current !== null) {
      if (current.data === data) {
        return current;
      }
      current = current.next;
    }
    return null;
  }

  isEmpty() {
    return this.head === null;
  }

  size() {
    let count = 0;
    let current = this.head;
    while (current !== null) {
      count++;
      current = current.next;
    }
    return count;
  }

  toString() {
    let string = '';
    let current = this.head;
    while (current !== null) {
      string += current.data + ' ';
      current = current.next;
    }
    return string;
  }
}

示例:使用队列和链表解决问题

我们可以使用队列和链表来解决各种各样的问题。例如,我们可以使用队列来模拟一个等待队列,或者使用链表来存储一个列表。

// 使用队列来模拟一个等待队列
const queue = new Queue();
queue.enqueue('John');
queue.enqueue('Mary');
queue.enqueue('Bob');

while (!queue.isEmpty()) {
  const customer = queue.dequeue();
  console.log('Now serving: ' + customer);
}

// 使用链表来存储一个列表
const list = new LinkedList();
list.append('Apple');
list.append('Orange');
list.append('Banana');

console.log('List: ' + list.toString());

结论

队列和链表都是非常重要的数据结构,它们在计算机科学中有着广泛的应用。我们可以在 JavaScript 中使用数组或链表来实现队列和链表,并利用它们来解决各种各样的问题。