Queue follows the FIFO approach, i.e first in first out approach. This is similar to a queue in the banking hall where the first customer in the queue is the first one to be served.
Queue Operations.
- Enqueue - Adding elements to the end of the queue.
- Dequeue - Removing elements from the Front of the queue.
- Peek - Returning the element in Front of the Queue without removing it.
- isEmpty - Check if the Queue is empty.
- isFull - Check if the Queue is Full.
Enqueue Operation
- Sent FRONT AND REAR pointer to track first and last elements.
- check if the queue is full using
isFull
. - Set the FRONT pointer to 0 for the first element.
- Increase the REAR pointer by 1.
- Point the REAR index to the new element.
Dequeue Operations.
- Use the
isEmpty
operation to check if the queue is empty. - Remove the element pointed by the FRONT index.
- Whenever an element is removed from the FRONT index should increase by 1.
- When removing the last element from the queue reset the FRONT and REAR pointer to -1.
Queue Implementation Using an Array.
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
return self.queue.append(item)
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop()
def size(self):
return len(self.queue)
def display(self):
return (self.queue)
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.enqueue(40)
print(q.display())
When using an array to implement the queue data structure, the complexity of the enqueue and dequeue operations isO(1)
.
Applications of the Queue Data Structure.
Handling Interrupts in real-time systems.
Used in the call center to hold people calling in an order.
Handling Interrupts in real-time systems.
Scheduling tasks in CPUs and Disks.
Top comments (0)