A Queue is a linear data structure that keeps its elements in a queue. It means that one end of a queue is used to add data into it and another end is used to remove data from it.
We often use queues in our everyday life. For example, queue at the supermarket, queue at the airport, and so on...
This ordering mechanism is also called FIFO (first-in-first-out) in which the first added element is processed first and the newest added element is processed last.
A Queue is like an array but with a few restrictions:
Operation | Description |
---|---|
enqueue(item) | add an item to the end of a queue |
dequeue() | remove the first item in a queue |
peek() | get an element that is in the front of a queue |
It can be used for any task where the first data/job that arrives needs to be processed first (FIFO). For example, it's possible to use a queue to upload images one by one in the order they arrived.
Operation | Complexity |
---|---|
Insertion | O(1) |
Deletion | O(1) |
*Access | O(n) |
import { LinkedList } from '../LinkedList/LinkedList';
export class Queue<T> {
private storage = new LinkedList<T>();
/**
* Add a new element to the end of the queue.
* This element will be processed after all elements that are already in the queue.
*/
public enqueue(value: T): void {
this.storage.append(value);
}
/** Remove the element that is at the front of queue. */
public dequeue(): T | null {
return this.storage.deleteHead()?.value || null;
}
/** Read the element at the front of the queue without removing it */
public peek(): T {
return this.storage.getFirst()?.value || null;
}
public isEmpty(): boolean {
return !this.storage.getFirst();
}
public size(): number {
return this.storage.toArray().length;
}
public toString(callback?: (val: T) => string): string {
return this.storage.toString(callback);
}
}