其他分享
首页 > 其他分享> > 队列

队列

作者:互联网

队列

/**
 * 创建队列
*/
class Queue {
  constructor() {
    // 队列当前索引
    this.count = 0
    // 队头索引
    this.lowestCount = 0
    // 存储队列
    this.items = {}
  }
  /**
   * 入队
  */
  enqueue(element) {
    this.items[this.count] = element
    this.count++
  }
  /**
   * 出队
  */
  dequeue() {
    if (this.isEmpty()) {
      return undefined
    }
    const result = this.items[this.lowestCount]
    delete this.items[this.lowestCount]
    this.lowestCount++
    return result
  }
  /**
   * 查看队头
  */
  peek() {
    if (this.isEmpty()) {
      return undefined
    }
    return this.items[this.lowestCount]
  }
  /**
   * 查看队列是否为空
  */
  isEmpty() {
    return this.count - this.lowestCount === 0
  }
  /**
   * 查看队列长度
  */
  size() {
    return this.count - this.lowestCount
  }
  /**
   * 清空队列
  */
  clear() {
    this.count = 0
    this.lowestCount = 0
    this.items = {}
  }
  toString() {
    let objString = ''
    for (let i = this.lowestCount; i < this.count; i++) {
      objString = objString + `,${this.items[i]}`
    }
    return objString
  }
}

const queue = new Queue()
queue.enqueue('a')
queue.enqueue('b')
queue.enqueue('c')
queue.enqueue('d')
queue.enqueue('e')
queue.enqueue('f')

console.log(queue.toString(), queue.size(), queue.peek(), queue.dequeue(), queue.items)

标签:count,return,队列,items,queue,enqueue,lowestCount
来源: https://www.cnblogs.com/JianXin1994/p/16273506.html