Like stacks, queues are abstract data structures. In a queue, the first element is inserted from one end, called REAR (also called the tail), and the removal of existing elements from the other end, is called FRONT (also called the head).
This makes the queue a FIFO (First In First Out) data structure, where the first element inserted is the first element removed.
Queue applications
Queues, as the name suggests, are used whenever we need to manage any group of objects on a first-come-first-served basis. Here are a few examples of the same:
- Serving requests on a single shared resource, such as a printer, CPU task scheduling, etc.
- In a real-life scenario, call centre phone systems use queues to queue people who call them, unless the service representative is free.
Algorithm for ENQUEUE operation
- Check if the queue is full or not.
- If the queue is full, then pop the first element / give an overflow error and exit the program.
- If you popped the first element, then increment the tail and add the element.
- If the queue is not full, then increment the tail and add the element.
Algorithm for DEQUEUE operation
- Check if the queue is empty or not.
- If the queue is empty, then print the underflow error and exit the program.
- If the queue is not empty, then print the element at the head and increment the head.
Time Complexity:
Enqueue: O(1)
Dequeue: O(1)
Size: O(1)
The functions associated with queue are:
empty() – Returns whether the stack is empty – Time Complexity: O(1)
size() – Returns the size of the stack – Time Complexity: O(1)
top() / peek() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
pop() – Deletes the topmost element of the stack – Time Complexity: O(1)
print - To print the stack
Top comments (0)