An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
September 25, 2021 02:13 pm GMT
Original Link: https://dev.to/bharathkumardamarla/implementation-of-queue-in-python-4h53
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 = Noneclass 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 operationx.display_queue(), x.show_front(), x.show_rear()
Output
Queue data: [7, 6, 5, 4, 3, 2, 1]front: 1rear: 7# after pop operationQueue data: [7, 6, 5, 4, 3, 2]front: 2rear: 7
Original Link: https://dev.to/bharathkumardamarla/implementation-of-queue-in-python-4h53
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To