队列是一种遵循先进先出 (FIFO) 原则的数据结构。
最先添加到队列中的元素也是最先被移除的。这就像排队买电影票一样,排在最前面的人先拿到票。
示例:实现队列
// program to implement queue data structure
class Queue {
constructor() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
//adds a new element
enqueue(element) {
this.items[this.tailIndex] = element;
this.tailIndex++;
}
//removes an element from head of the queue
dequeue() {
let removedElement = this.items[this.headIndex];
delete this.items[this.headIndex];
this.headIndex++;
return removedElement;
}
//shows the head element of the queue
peek() {
let peekElement = this.items[this.headIndex];
return peekElement;
}
//shows the number of items in queue
size() {
return this.tailIndex - this.headIndex;
}
//checks if queue is empty or not
isEmpty() {
if (this.tailIndex - this.headIndex == 0) {
return true;
}
else {
return false;
}
}
//empty the queue
clear() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
}
let queue = new Queue();
// add items to queue
queue.enqueue(8);
queue.enqueue(6);
queue.enqueue(4);
queue.enqueue(2);
console.log("Queue after adding items: ");
console.log(queue.items);
// remove the first item
queue.dequeue();
console.log("Queue after deleting the first item:");
console.log(queue.items);
// show the first item
console.log("First item of the queue = " + queue.peek());
// empty the queue
queue.clear();
console.log("After clearing the queue: ");
console.log(queue.items);
输出
Queue after adding items: { '0': 8, '1': 6, '2': 4, '3': 2 } Queue after deleting the first item: { '1': 6, '2': 4, '3': 2 } First item of the queue = 6 After clearing the queue: {}
在上面的程序中,队列数据结构是使用对象实现的。创建了Queue
类来实现队列数据结构。该类包含enqueue()
、dequeue()
、peek()
、isEmpty()
、size()
和clear()
等方法。
使用new
运算符创建Queue
对象,并通过该对象访问各种方法。
- 最初,
this.items
是一个空对象,被视为队列。 enqueue()
方法将元素添加到队列中。dequeue()
方法从队列中移除第一个元素。peek()
方法返回队列中的第一个元素。size()
方法显示队列中的元素总数。isEmpty()
方法返回一个布尔值,检查队列是否为空。clear()
方法用于清空并重置队列。
另请阅读