CHAPTER 4: QUEUE
CHAPTER NOTES
4.1 Introduction to Queue
• A Queue is an ordered linear data structure that follows the FIFO (First In First Out)
principle.
• Items are inserted at the rear (tail) and removed from the front (head).
• Real-life Examples: Bank queues, toll booths, printer tasks, IVRS systems.
4.1.1 FIFO Principle
• First-In-First-Out: The element added first is the one removed first.
• Implemented using two ends:
– REAR (TAIL) → for insertion
– FRONT (HEAD) → for deletion
Applications of Queue
Real-Life Applications
1. Train Ticket Waiting List
• When you book a ticket and it shows W/L1, it means your request is added to a queue.
• If someone cancels their confirmed ticket, the one at the front of the queue (like W/L1) gets
confirmed.
• This strictly follows the First-In-First-Out (FIFO) principle.
2. Customer Care Calls (IVRS Systems)
• When you call a customer care number, you might hear: > ―Please wait while your call is
transferred…‖
• Your call is placed in a queue.
• As soon as a customer care executive is free, the first caller in the queue is attended.
3. Traffic Management (One-Way Road or Toll Booth)
• Vehicles on a one-way street or at a fuel pump/toll plaza form a queue.
• The vehicle that arrived first gets to move first.
Applications in Computer Science
1. Web Server Request Handling
• A server can handle only a limited number of simultaneous requests (say 50).
• If 1000 students try to check results at the same time, the server keeps extra requests in a
queue.
• These requests are served one by one as per FIFO.
2. CPU Task Scheduling in Operating Systems
• When multiple programs (called jobs) request CPU time, only one can run at a time.
• Jobs are queued and the CPU executes them in the order they arrive (simple job scheduling).
3. Printer Queue Management
• If multiple print requests are sent to a shared printer:
– The first print command sent is executed first.
– Remaining ones wait in the print queue.
4.2 Operations on Queue
Operation Description
enqueue() Insert an element at rear. Exception: Overflow if full (static case).
dequeue() Remove from front. Exception: Underflow if empty.
isEmpty() Check if queue is empty.
peek() View the front item without removing.
isFull() Check if queue is full (not required in Python list-based queue).
Visual Example (Queue of alphabets):
enqueue('Z') → Z
enqueue('X') → Z X
enqueue('C') → Z X C
dequeue() → X C
enqueue('V') → X C V
4.3 Implementation of Queue using Python
myQueue = list()
def enqueue(myQueue, element):
myQueue.append(element)
def isEmpty(myQueue):
return len(myQueue) == 0
def dequeue(myQueue):
if not isEmpty(myQueue):
return myQueue.pop(0)
else:
print("Queue is empty")
def size(myQueue):
return len(myQueue)
def peek(myQueue):
if isEmpty(myQueue):
print("Queue is empty")
return None
else:
return myQueue[0]
Program 4-1: Simulation of a Queue in a Bank
myQueue = list()
element = input("Enter person’s code to enter in queue: ")
enqueue(myQueue, element)
element = input("Enter person’s code for insertion in queue: ")
enqueue(myQueue, element)
print("Person removed from queue is:", dequeue(myQueue))
print("Number of people in the queue is:", size(myQueue))
for _ in range(3):
element = input("Enter person’s code to enter in queue: ")
enqueue(myQueue, element)
print("Now removing remaining people from queue:")
while not isEmpty(myQueue):
print("Person removed from queue is", dequeue(myQueue))
4.4 Introduction to Deque (Double-Ended Queue)
• Deque allows insertion and deletion from both ends – front and rear.
• Can behave as both:
– Stack (LIFO): insertion/deletion at same end.
– Queue (FIFO): insertion/deletion at opposite ends.
Applications of Deque (Double-Ended Queue)
Real-Life Applications
1. Re-entry at Ticket Counter
• A person buys a ticket, leaves, and then comes back with a query.
• Since they’ve already been served, they might get the privilege to rejoin from the front, not
the rear.
• This needs a data structure where you can insert from either end — a deque.
2. Toll Booth Queue Redirection
• Suppose multiple toll booths exist.
• If one booth clears early, vehicles from the rear of other queues might shift to the front of
the vacant booth’s queue.
• This needs both front and rear insertions/deletions, which is deque-like behavior.
Applications in Computer Science
1. Browser History Navigation
• URLs are added to a stack-like structure, but if the memory is limited, older entries (from
the rear) must be removed.
• Deque can store history and remove least-recently-used entries when full.
2. Undo/Redo in Text Editors
• Operations are stored so that the last action can be undone first, like a stack.
• But to manage multiple undo/redo and limited memory, deque provides efficient handling.
3. Palindrome Checking
• A string is inserted character by character into a deque.
• Then characters are compared from front and rear simultaneously.
• If they match all the way, the string is a palindrome.
• Deque allows accessing both ends easily.
4.4.2 Operations on Deque
Operation Description
------------------ --------------------------------
insertFront() Insert at front
insertRear() Insert at rear
deletionFront() Delete from front
deletionRear() Delete from rear
isEmpty() Check if deque is empty
getFront() View front without removing
getRear() View rear without removing
Algorithm 4.1: Palindrome using Deque
1. Traverse string left to right.
2. Insert each character at rear.
3. Repeat: delete character from both front and rear, compare.
4. If all pairs match → it’s a palindrome.
4.5 Implementation of Deque using Python
def insertFront(myDeque, element):
myDeque.insert(0, element)
def insertRear(myDeque, element):
myDeque.append(element)
def isEmpty(myDeque):
return len(myDeque) == 0
def deletionRear(myDeque):
if not isEmpty(myDeque):
return myDeque.pop()
else:
print("Deque empty")
def deletionFront(myDeque):
if not isEmpty(myDeque):
return myDeque.pop(0)
else:
print("Deque empty")
def getFront(myDeque):
if not isEmpty(myDeque):
return myDeque[0]
else:
print("Queue empty")
def getRear(myDeque):
if not isEmpty(myDeque):
return myDeque[-1]
else:
print("Deque empty")
Program 4-2: Menu-driven Deque Program
def main():
dQu = list()
choice = int(input("Enter 1 to use as queue, 2 otherwise: "))
if choice == 1:
element = input("Data for insertion at rear: ")
insertRear(dQu, element)
print("Data at front:", getFront(dQu))
element = input("Data for insertion at rear: ")
insertRear(dQu, element)
print("Removed:", deletionFront(dQu))
print("Removed:", deletionFront(dQu))
else:
element = input("Data for insertion at front: ")
insertFront(dQu, element)
print("Data at rear:", getRear(dQu))
element = input("Data for insertion at front: ")
insertFront(dQu, element)
print("Removed:", deletionRear(dQu))
print("Removed:", deletionRear(dQu))
2 MARKS QUESTIONS
Q1. What is meant by the FIFO principle in the context of queues? Explain with an
example.
Answer:
FIFO stands for First-In-First-Out, meaning the element that enters the queue first is the one
that exits
first.
Example: In a bank queue, the first customer to enter the line is the first to be served at the
counter.
Q2. Differentiate between Queue and Stack.
Answer:
Queue Stack
Follows FIFO (First In First Out) Follows LIFO (Last In First Out)
Insertion at rear, deletion at front Insertion and deletion at same end
Q3. What is underflow and when does it occur in a queue?
Answer:
Underflow is an error that occurs when a dequeue operation is attempted on an empty queue,
i.e., when
there are no elements to remove.
Q4. Name any four operations supported by a queue.
Answer:
The four operations are:
1. enqueue() – to insert an element
2. dequeue() – to delete an element
3. peek() – to view the front element
4. isEmpty() – to check if the queue is empty
Q5. Write the syntax of a function to insert an element at the rear of a queue in Python.
Answer:
def enqueue(myQueue, element):
myQueue.append(element)
Here, append() adds the element at the end (rear) of the list used as a queue.
Q6. Write a Python function to check whether a queue is empty or not.
Answer:
def isEmpty(myQueue):
if len(myQueue) == 0:
return True
else:
return False
Q7. What is a deque? Mention one of its applications.
Answer:
A deque (double-ended queue) is a linear data structure that allows insertion and deletion
from both
front and rear ends.
Application: Checking whether a string is a palindrome using character comparisons from both
ends.
Q8. Give the syntax of the deletion from rear operation in a deque using Python.
Answer:
def deletionRear(myDeque):
if not isEmpty(myDeque):
return myDeque.pop()
else:
print("Deque empty")
Q9. Distinguish between insertFront() and insertRear() in deque.
Answer:
insertFront() insertRear()
Inserts element at the front of
deque
Inserts element at the rear of deque
Uses insert(0, element) Uses append(element)
Q10. What does the peek() function do in a queue? Provide its implementation.
Answer:
peek() is used to view the front element of the queue without removing it.
def peek(myQueue):
if isEmpty(myQueue):
print("Queue is empty")
return None
else:
return myQueue[0]
3 MARKS QUESTIONS
Q1. Define a queue. How does it differ from a stack?
Answer:
A queue is an ordered linear data structure that follows the FIFO (First-In-First-Out) principle.
In a
queue, insertion takes place at the rear and deletion occurs from the front.
Difference between queue and stack:
Queue Stack
Follows FIFO Follows LIFO
Insertion at rear, deletion at front Insertion and deletion at the same end
Used in print queues, job scheduling Used in undo operations, expression evaluation
Q2. Explain the operations enqueue(), dequeue(), and peek() in the context of queue
implementation
in Python.
Answer:
• enqueue() inserts an element at the rear of the queue:
def enqueue(myQueue, element):
myQueue.append(element)
• dequeue() removes and returns the front element:
def dequeue(myQueue):
if not isEmpty(myQueue):
return myQueue.pop(0)
else:
print("Queue is empty")
• peek() returns the front element without removing it:
def peek(myQueue):
if isEmpty(myQueue):
print("Queue is empty")
return None
else:
return myQueue[0]
Q3. Describe any three real-life or computer science applications of queues.
Answer:
1. Customer Care Calls: Incoming calls are put in a queue and served in FIFO order.
2. Print Queue: Multiple print requests from different users are queued and printed one by one.
3. Operating System Task Scheduling: In multitasking systems, jobs are queued for processor
time
in FIFO order.
Q4. What is a deque? Explain with two relevant operations and their Python
implementations.
Answer:
A deque (double-ended queue) allows insertion and deletion from both front and rear.
• insertFront():
def insertFront(myDeque, element):
myDeque.insert(0, element)
• deletionRear():
def deletionRear(myDeque):
if not isEmpty(myDeque):
return myDeque.pop()
else:
print("Deque empty")
Q5. Compare queue and deque based on structure and operations.
Answer:
Aspect Queue Deque
Structure Linear structure with two ends Linear, double-ended structure
Insertion At rear only At both front and rear
Deletion From front only From both front and rear
Flexibility Less flexible More flexible, supports stack
and queue behavior
Q6. Write the complete Python function to check if a queue is empty and to return its size.
Answer:
• isEmpty():
def isEmpty(myQueue):
if len(myQueue) == 0:
return True
else:
return False
• size():
def size(myQueue):
return len(myQueue)
These functions help prevent underflow and allow queue size tracking.
Q7. Describe the steps of palindrome checking using deque.
Answer:
1. Traverse the string character by character.
2. Insert each character into the deque from the rear.
3. Remove one character from the front and one from the rear, and compare.
4. Repeat until all characters are compared or only one remains.
5. If all pairs match, the string is a palindrome; otherwise, it’s not.
Q8. What are the roles of getFront() and getRear() in a deque? Provide their syntax.
Answer:
• getFront(): Returns the front element without deleting it.
def getFront(myDeque):
if not isEmpty(myDeque):
return myDeque[0]
else:
print("Queue underflow")
• getRear(): Returns the rear element without deleting it.
def getRear(myDeque):
if not isEmpty(myDeque):
return myDeque[len(myDeque) - 1]
else:
print("Deque empty")
These functions are useful for reading elements safely in a deque.