赞
踩
队列(Queue)是一种先进先出(First In First Out, FIFO)的数据结构,它按照元素进入的顺序来处理元素。队列的基本操作包括:
数组实现队列
class Queue { contructor(){ this._queue = []; } isEmty() { return this._queue.length === 0; } enqueue(value) { this._queue.push(value); } dequeue() { if (this.isEmty()) { return undefined; } return this._queue.shift(); } size() { return this._queue.length; } peek() { if (this.isEmty()) { return undefined; } return this._queue[0]; } }
链表实现队列
class Node { constructor(value){ this.value = value; this.next = null; } } class Queue { contructor(){ this._front = null this._rear = null this._size = 0 } isEmty() { return this._size === 0; } size() { return this._size; } dequeue() { if (this.isEmty()) { return undefined; } this._size-- const removeNode = this._front this._front = this._front.next if (this.isEmty()) { this._rear = null } return removeNode.value; } enqueue(value) { const newNode = new Node(value) if (this.isEmty()) { this._front = newNode this._rear = newNode } else { this._rear.next = newNode this._rear = newNode } this._size++ } peek() { if (this.isEmty()) { return undefined; } return this._front.value; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。