队列

278 阅读1分钟

队列可以用数组来实现,也可以用链表来实现。用数组实现的栈叫作顺序栈,用链表实现的栈叫作链式栈。同样,用数组实现的队列叫作顺序队列,用链表实现的队列叫作链式队列。 用数组实现

class ArrayQueue {
  constructor(capacity){
    this.capacity = capacity;
    this.items = [];
    this.head = -1;
    this.tail = -1;
  }
  pushQueue(item){
    if (this.tail === this.capacity){
      if (this.head === 0){
        return false;
      }
      for (let i = this.head; i <= this.tail; i++){
        this.items[i - this.head] = this.items[i];
      }
      this.tail = this.tail - this.head;;
      this.head = 0;
    }
    this.items[this.tail] = item;
    this.tail++;
    return true;
  }
  popQueue(item){
    if (this.tail === this.head){
      return undefined;
    }
    let value = this.items[this.head]
    this.head--;
    return value;
  }
}

用链表实现

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

class LinkedList{
  constructor(){
    this.head = null;
    this.tail = null;
  }
  push(item){
    if (this.tail === null){
      this.tail = new Node(item);
      this.head = this.tail;
    } else {
      this.tail.next = new Node(item);
      this.tail = this.tail.next;
    }
  }
  pop (){
    if (this.head !== null){
      let item = this.head.element;
      this.head = this.head.next;
      return item;
    }
    return -1;
  }

}