乐闻世界logo
搜索文章和话题

How to Implement a Queue Using JavaScript

2024年7月4日 09:35

A queue is a data structure that follows the First-In-First-Out (FIFO) principle. In JavaScript, arrays can be used to implement various queue operations. Here is a simple example of implementing a queue, including enqueue, dequeue, peek, isEmpty, and size methods:

javascript
class Queue { constructor() { this.items = []; // Using an array to store queue elements } // Enqueue operation enqueue(element) { this.items.push(element); } // Dequeue operation dequeue() { if (this.isEmpty()) { return 'Queue is empty'; } return this.items.shift(); } // Peek at the front element peek() { if (this.isEmpty()) { return 'Queue is empty'; } return this.items[0]; } // Check if the queue is empty isEmpty() { return this.items.length === 0; } // Get the size of the queue size() { return this.items.length; } } // Usage example const queue = new Queue(); queue.enqueue('John'); queue.enqueue('Jack'); console.log(queue.peek()); // Output: John queue.dequeue(); console.log(queue.peek()); // Output: Jack console.log(queue.isEmpty()); // Output: false console.log(queue.size()); // Output: 1

In this example, we define a Queue class with several methods to simulate queue behavior. The enqueue method adds a new element to the queue, dequeue removes the front element, peek returns the front element without removing it, isEmpty checks if the queue is empty, and size returns the current number of elements in the queue. This implementation uses arrays to simulate typical queue operations as closely as possible.

标签:数据结构