PHP前端开发

js如何定义队列

百变鹏仔 4天前 #JavaScript
文章标签 队列
队列在 javascript 中是一种先进先出(fifo)的数据结构。使用数组实现队列,队列操作包括入队、出队、队首元素和队列大小。使用链表实现队列可以更有效地处理大型队列。

JavaScript 定义队列

在 JavaScript 中,队列是一种先进先出(FIFO)的数据结构,这意味着最早添加的元素将第一个被删除。以下是定义队列的方法:

数组实现

使用数组可以轻松定义一个队列:

const queue = [];

队列操作:

链表实现

使用链表可以实现更有效的队列,特别是当队列很大时:

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;  }}