Queues
A Queue is a Linear Data Structure that follows the principle of FIFO or the First-In and First-Out Principle. The values can be added to the rear of the queue (Enqueue) and the values can be removed from the front of the queue (Dequeue). We will use a queue queue of fixed length 4. The various operations that can be performed on a Queue are :
-Enqueue: In this process, a value is put into the queue from the rear or the back of the queue.
global queue
if(len(queue)==4):
print(“Cannot perform action, queue is full“)
else:
a = int(input(“Enter value: “))
# adds value to the end (rear) of the queue
queue.append(a)
print(f“{a} added to rear of the queue“)
-Dequeue: In this process, a value is removed from the front of the queue.
global queue
if len(queue) == 0:
print(“Cannot perform action, queue is empty“)
else:
print(f“Dequeued value: {queue[0]}“)
# removes the value from the front of the queue
queue.pop(0)
-Peek: In this process, the value at the front of the queue is displayed.
global queue
if len(queue) == 0:
print(“Queue is empty“)
else:
print(f“Front value of Queue: {queue[0]}“)
-Rear: In this process, the value at the rear of the queue is displayed.
global queue
if len(queue) == 0:
print(“Queue is empty“)
else:
print(f“Rear value of Queue: {queue[–1]}“)
-State_of_Queue: This function combines the operations is_empty(), which tells you whether or not the queue is empty, and is_full(), which tells you whether or not the queue is full. The function of the operation is:
if len(queue) == 4:
print(“Queue is full“)
elif len(queue) == 0:
print(“Queue is empty“)
else:
print(“Queue is partially empty“)
To simulate the functioning of a queue, the complete code is given below:
## Global variables
queue = ar.array(‘i‘, [])
def enqueue():
global queue
if(len(queue)==4):
print(“Cannot perform action, queue is full“)
else:
a = int(input(“Enter value: “))
# adds value to the end (rear) of the queue
queue.append(a)
print(f“{a} added to rear of the queue“)
def dequeue():
global queue
if len(queue) == 0:
print(“Cannot perform action, queue is empty“)
else:
print(f“Dequeued value: {queue[0]}“)
# removes the value from the front of the queue
queue.pop(0)
def peek():
global queue
if len(queue) == 0:
print(“Queue is empty“)
else:
print(f“Front value of Queue: {queue[0]}“)
def rear():
global queue
if len(queue) == 0:
print(“Queue is empty“)
else:
print(f“Rear value of Queue: {queue[–1]}“)
def state_of_queue():
if len(queue) == 4:
print(“Queue is full“)
elif len(queue) == 0:
print(“Queue is empty“)
else:
print(“Queue is partially empty“)
## Driver Code
while True:
print(“1.Enqueuen2.Dequeuen3.Peekn4.Rearn5.State of Queuen6.Exit“)
ch = int(input(“Enter choice: “))
if ch == 1:
enqueue()
elif ch == 2:
dequeue()
elif ch == 3:
peek()
elif ch == 4:
rear()
elif ch == 5:
state_of_queue()
else:
break
Another type of queue is called as a circular queue and can be read here