关于javascript:javascript-数据结构系列-三-队列

53次阅读

共计 1102 个字符,预计需要花费 3 分钟才能阅读完成。

明天持续 javascript 数据结构系列队列,概念性货色其余文章都有介绍,这里就不在具体介绍,间接看一下代码实现
首先,队列构造函数,代码实现如下

export default class Queue {constructor() {
    // We're going to implement Queue based on LinkedList since the two
    // structures are quite similar. Namely, they both operate mostly on
    // the elements at the beginning and the end. Compare enqueue/dequeue
    // operations of Queue with append/deleteHead operations of LinkedList.
    this.linkedList = new LinkedList();}
 }

其次,判断队列是否为空 isEmpty 办法

  /**
   * @return {boolean}
   */
  isEmpty() {return !this.linkedList.head;}

peek 办法,在不删除 i 的状况下,读取队列后面的元素

  /**
   * Read the element at the front of the queue without removing it.
   * @return {*}
   */
  peek() {if (!this.linkedList.head) {return null;}

    return this.linkedList.head.value;
  }

enqueue 办法队列开端增加元素

  /**
   * Add a new element to the end of the queue (the tail of the linked list).
   * This element will be processed after all elements ahead of it.
   * @param {*} value
   */
  enqueue(value) {this.linkedList.append(value);
  }

dequeue 删除队列后面的元素

  /**
   * Remove the element at the front of the queue (the head of the linked list).
   * If the queue is empty, return null.
   * @return {*}
   */
  dequeue() {const removedHead = this.linkedList.deleteHead();
    return removedHead ? removedHead.value : null;
  }

至此,一个简略队列数据几个曾经实现实现,敬请关注,后续持续推出其它数据结构系列文章,如果有帮忙请点赞!

正文完
 0