博客说明

由于最近开始练习写作,文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除!

今天继续 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;
  }

至此,一个简单队列数据几个已经实现完成,敬请关注,后续继续推出其它数据结构系列文章,如果有帮助请点赞!


henry_57bcfc6a67f76
1 声望0 粉丝