## DEV Community

BHARATH KUMAR DAMARLA

Posted on

# Implementation of Queue in python

1.Queue is a type of data structure.Queue is based on the principle first in first out (FIFO) i.e first inserted element will be deleted first.

2.In queue Insertion of elements is done at one end i.e rear and deleting of elements is done at other end
i.e front.

3.Queue works similar to queue at a ticket counter the first person in the queue is the front and the last person is the rear.

Now let us look at some example to implement a queue using a LinkedList

## Example:

``````class node:
def __init__(self,val):
self.val = val
self.next = None

class queue:
def __init__(self):
self.front = None
self.rear = None

# push element on rear side
def push(self,val):
if (self.rear == None):
self.front = node(val)
self.rear = self.front
else:
new_node = node(val)
self.rear.next = new_node
self.rear = self.rear.next

# pop deletes the first inserted element in queue in front side
def pop(self):
if (self.front == None):
print('No elements to pop in Queue')

else:
self.front = self.front.next

# To show where front is currently at
def show_front(self):
print('front: ',self.front.val)

# To show where rear is currently at
def show_rear(self):
print('rear: ', self.rear.val)

def display_queue(self):
# To display the whole queue we have to traverse the linkedList
# Using a dummy node starting from head
q = []
dummy = self.front
while(dummy):
q.append(dummy.val)
dummy = dummy.next
# Reverse 'q' to avoid confusion
q.reverse()
print('Queue data: ', q)
``````

### Input

``````x = queue() # instantiates a queue object named 'x'
x.push(1)
x.push(2)
x.push(3)
x.push(4)
x.push(5)
x.push(6)
x.push(7)

x.display_queue(), x.show_front(), x.show_rear()
x.pop()
# front is changed after pop operation
x.display_queue(), x.show_front(), x.show_rear()
``````

### Output

``````Queue data:  [7, 6, 5, 4, 3, 2, 1]
front:  1
rear:  7
# after pop operation
Queue data:  [7, 6, 5, 4, 3, 2]
front:  2
rear:  7
``````