DEV Community

Karhik Suryadevara
Karhik Suryadevara

Posted on • Updated on

Implementation of Queue in python

queue image

  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 the code to implement a queue using a LinkedList.

Code

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)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Top comments (0)