js 数组和链表分别实现队列

发布时间 2023-07-01 12:12:54作者: 浅唱年华1920

链表实现

/**
 * 链表实现队列
 * 1.从尾入,头出
 * 2.单独记录length
 */
class MyQueue {
  head = null; //
  tail = null; //
  len = 0;
  add(n) {
    let newNode = {
      value: n,  // 因为是最后一级,没有next
    };
    // 处理head 如果入队的时候头是空的,给头直接赋值
    if (this.head == null) {
      this.head = newNode;
    }
    // 处理tail
    let tailNode = this.tail;
    if (tailNode) {
      tailNode.next = newNode;
    }
    this.len++;
    this.tail = newNode; 
  }
  delete() {
    let headNode = this.head;
    if (headNode == null) return null;
    if (this.len == 0) return null;
    // 取值
    const value = headNode.value;
    // 处理head
    this.head = headNode.next;
    this.len--;
    headNode = null
    return value
  }
  length() {
    // length 单独存储,不能通过遍历链表来获取length(否则时间复杂度O(n))
    return this.len;
  }
}

数组实现