队列在 JavaScript 中是一种先进先出(FIFO)的数据结构。使用数组实现队列,队列操作包括入队、出队、队首元素和队列大小。使用链表实现队列可以更有效地处理大型队列。

JavaScript 定义队列
在 JavaScript 中,队列是一种先进先出(FIFO)的数据结构,这意味着最早添加的元素将第一个被删除。以下是定义队列的方法:
数组实现
使用数组可以轻松定义一个队列:
const queue = [];
队列操作:
-
入队(enqueue):将元素推入数组的末尾。
jQuery创建模态窗口登陆效果下载何利用jQuery插件leanModal建立一个常规模态窗口。如果你有MIT general license,那么这个插件是完全开源和免费的,我很喜欢这个插件,用起来相当方便,还能自行添加CSS,达到自定义的效果。
queue.push(element);
-
出队(dequeue):删除数组的第一个元素。
queue.shift();
-
队首元素(peek):查看队列中第一个元素。
queue[0];
-
队列大小(size):返回队列中元素的数量。
queue.length;
链表实现
使用链表可以实现更有效的队列,特别是当队列很大时:
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
}
enqueue(element) {
const newNode = new Node(element);
if (this.tail) this.tail.next = newNode;
this.tail = newNode;
if (!this.head) this.head = newNode;
}
dequeue() {
if (!this.head) return;
const value = this.head.value;
this.head = this.head.next;
if (!this.head) this.tail = null;
return value;
}
peek() {
if (!this.head) return;
return this.head.value;
}
size() {
let count = 0;
let current = this.head;
while (current) {
count++;
current = current.next;
}
return count;
}
}









