js实现queue
实现队列的基本方法
队列是一种先进先出(FIFO)的数据结构,JavaScript中可以通过数组或链表实现。以下是两种常见的实现方式:
使用数组实现队列
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
return this.items.shift();
}
front() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}
使用链表实现队列
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedListQueue {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
enqueue(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
}
dequeue() {
if (!this.head) return null;
const temp = this.head;
this.head = this.head.next;
this.length--;
if (!this.head) {
this.tail = null;
}
return temp.value;
}
peek() {
return this.head ? this.head.value : null;
}
isEmpty() {
return this.length === 0;
}
size() {
return this.length;
}
}
队列的变种实现
循环队列实现
class CircularQueue {
constructor(k) {
this.size = k;
this.queue = new Array(k);
this.head = -1;
this.tail = -1;
}
enQueue(value) {
if (this.isFull()) return false;
if (this.isEmpty()) this.head = 0;
this.tail = (this.tail + 1) % this.size;
this.queue[this.tail] = value;
return true;
}
deQueue() {
if (this.isEmpty()) return false;
if (this.head === this.tail) {
this.head = -1;
this.tail = -1;
return true;
}
this.head = (this.head + 1) % this.size;
return true;
}
Front() {
return this.isEmpty() ? -1 : this.queue[this.head];
}
Rear() {
return this.isEmpty() ? -1 : this.queue[this.tail];
}
isEmpty() {
return this.head === -1;
}
isFull() {
return (this.tail + 1) % this.size === this.head;
}
}
优先队列实现
优先队列中元素具有优先级,优先级高的先出队:
class PriorityQueue {
constructor() {
this.items = [];
}
enqueue(element, priority) {
const queueElement = { element, priority };
let added = false;
for (let i = 0; i < this.items.length; i++) {
if (queueElement.priority < this.items[i].priority) {
this.items.splice(i, 0, queueElement);
added = true;
break;
}
}
if (!added) {
this.items.push(queueElement);
}
}
dequeue() {
return this.items.shift();
}
front() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
队列的性能优化
数组实现的shift()操作时间复杂度为O(n),对于频繁出队的场景,可以使用双指针技术优化:
class OptimizedQueue {
constructor() {
this.items = {};
this.head = 0;
this.tail = 0;
}
enqueue(element) {
this.items[this.tail] = element;
this.tail++;
}
dequeue() {
if (this.isEmpty()) return undefined;
const item = this.items[this.head];
delete this.items[this.head];
this.head++;
return item;
}
peek() {
return this.items[this.head];
}
isEmpty() {
return this.tail - this.head === 0;
}
size() {
return this.tail - this.head;
}
}
这些实现涵盖了队列的基本操作和常见变种,可根据具体需求选择合适的实现方式。数组实现简单直观,链表实现避免了数组的shift开销,而双指针优化则进一步提升了性能。







