如何使用数组实现JavaScript队列
一、队列数据结构简介
队列是元素的有序列表,其中元素插入到队列的末尾,并从队列的前面删除。
与基于先进先出(LIFO)原理工作的堆栈不同,队列基于先进先出(FIFO)原理工作。
队列有两个主要操作,涉及插入新元素和删除现有元素。
插入操作称为enqueue,而删除操作称为dequeue。入队操作在队列的末尾插入一个元素,而出队操作从队列的前部删除一个元素。
下图说明了一个队列:
js数组中实现一个堆栈和队列的操作示例代码:
var stack = []; stack.push(2); // stack is now [2] stack.push(5); // stack is now [2, 5] var i = stack.pop(); // stack is now [2] alert(i); // displays 5 var queue = []; queue.push(2); // queue is now [2] queue.push(5); // queue is now [2, 5] var i = queue.shift(); // queue is now [5] alert(i); // displays 2
您可以通过使用Array类型的两个方法来将数组用作队列:
使用push()方法在数组的末尾添加一个元素。此方法等效于入队操作。
使用shift()方法从数组的开头删除元素 。与出队操作相同。
让我们通过使用数组来实现JavaScript队列数据结构。
以下是队列的构造函数:
function Queue() { this.elements = []; }
Queue.prototype.enqueue = function (e) { this.elements.push(e); };
Queue.prototype.dequeue = function () { return this.elements.shift(); };
Queue.prototype.isEmpty = function () { return this.elements.length == 0; };
Queue.prototype.peek = function () { return !this.isEmpty() ? this.elements[0] : undefined; };
Queue.prototype.length = function() { return this.elements.length; }
let q = new Queue(); //要排队1到7之间的数字,请使用以下代码。 for (let i = 1; i <= 7; i++) { q.enqueue(i); }
console.log(q.peek()); // 1
console.log(q.length()); // 7
while (!q.isEmpty()) { console.log(q.dequeue()); }
网友评论0