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

JavaScript 定义队列
在 JavaScript 中,队列是一种先进先出(FIFO)的数据结构,这意味着最早添加的元素将第一个被删除。以下是定义队列的方法:
数组实现
使用数组可以轻松定义一个队列:
const queue = [];
队列操作:
-
入队(enqueue):将元素推入数组的末尾。
e新时代企业网站管理系统6.0 ACC版下载系统共有:常规管理,公告管理,新闻管理,产品管理,采购订单管理,留言反馈管理,短信管理,用户管理,管理员管理,在线邮件管理,系统模板管理,图品缩略图及水印管理,Flash幻灯片管理,统计调查管理,系统数据调用管理,自定义扩展管理,语言标签库管理。18个主要功能模块组成。5月10号更新:1、全新双语模式设计开发2、多级动态JS菜单,支持在线添加,修改,删除3、新增单页管理模块,如扩展企业简介,联系方
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;
}
}









