队列和堆栈类似,但是它是一种先进先出的结构。FIFO (first in first out)。
代码实现,javascript
class Queue { constructor() { this.items = new LinkedList(); } clear() { this.items = new LinkedList(); } contains(item) { return this.items.contains(item); } peek() { return this.items.head.data; } dequeue() { let removedItem = this.items.head.data; this.items.removeFirst(); return removedItem; } enqueue(item) { this.items.addLast(item); } getLength() { return this.items.length; } }
使用Queue
// create new Queue object let myQ = new Queue(); // add two items myQ.enqueue("Item 1"); myQ.enqueue("Item 2"); // remove item let removedItem = my.dequeue(); // returns Item 1
时间复杂度
行为 | 最佳 | 平均 | 最差 |
Enqueue (Insert) | O(1) | O(1) | O(1) |
Dequeue (Remove) | O(1) | O(1) | O(1) |
Peek | O(1) | O(1) | O(1) |
Search / Contains | O(1) | O(n) | O(n) |
Memory | O(n) | O(n) | O(n) |