|
| 1 | +# Copyright (C) Deepali Srivastava - All Rights Reserved |
| 2 | +# This code is part of DSA course available on CourseGalaxy.com |
| 3 | + |
| 4 | +class EmptyQueueError(Exception): |
| 5 | + pass |
| 6 | + |
| 7 | +class Node: |
| 8 | + |
| 9 | + def __init__(self,value,pr): |
| 10 | + self.info = value |
| 11 | + self.priority = pr |
| 12 | + self.link = None |
| 13 | + |
| 14 | +class PriorityQueue: |
| 15 | + |
| 16 | + def __init__(self): |
| 17 | + self.front = None |
| 18 | + |
| 19 | + def enqueue(self, data, data_priority): |
| 20 | + |
| 21 | + temp = Node(data, data_priority) |
| 22 | + |
| 23 | + #If queue is empty or element to be added has priority more than first element |
| 24 | + if self.is_empty() or data_priority < self.front.priority: |
| 25 | + temp.link = self.front |
| 26 | + self.front = temp |
| 27 | + else: |
| 28 | + p = self.front |
| 29 | + while p.link != None and p.link.priority <= data_priority: |
| 30 | + p = p.link |
| 31 | + temp.link = p.link |
| 32 | + p.link = temp |
| 33 | + |
| 34 | + def dequeue(self): |
| 35 | + if self.is_empty(): |
| 36 | + raise EmptyQueueError("Queue is empty") |
| 37 | + x = self.front.info |
| 38 | + self.front = self.front.link |
| 39 | + return x |
| 40 | + |
| 41 | + def is_empty(self): |
| 42 | + return self.front == None |
| 43 | + |
| 44 | + def display(self): |
| 45 | + if self.is_empty(): |
| 46 | + print("Queue is empty") |
| 47 | + return |
| 48 | + |
| 49 | + print("Queue is : ") |
| 50 | + p = self.front |
| 51 | + while p is not None: |
| 52 | + print(p.info , " ", p.priority) |
| 53 | + p = p.link |
| 54 | + print() |
| 55 | + |
| 56 | + def size(self): |
| 57 | + n = 0 |
| 58 | + p = self.front |
| 59 | + while p is not None: |
| 60 | + n+=1 |
| 61 | + p = p.link |
| 62 | + return n |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | +######################################################################################### |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + qu = PriorityQueue() |
| 70 | + |
| 71 | + while True: |
| 72 | + print("1.Enqueue") |
| 73 | + print("2.Dequeue") |
| 74 | + print("3.Display all queue elements") |
| 75 | + print("4.Display size of the queue") |
| 76 | + print("5.Quit") |
| 77 | + |
| 78 | + choice = int(input("Enter your choice : ")) |
| 79 | + |
| 80 | + if choice == 1: |
| 81 | + x = int(input("Enter the element : ")) |
| 82 | + pr = int(input("Enter its priority : ")) |
| 83 | + qu.enqueue(x,pr) |
| 84 | + elif choice == 2: |
| 85 | + x=qu.dequeue() |
| 86 | + print("Element is : " , x) |
| 87 | + elif choice == 3: |
| 88 | + qu.display() |
| 89 | + elif choice == 4: |
| 90 | + print("Size of queue " , qu.size()) |
| 91 | + elif choice == 5: |
| 92 | + break; |
| 93 | + else: |
| 94 | + print("Wrong choice") |
| 95 | + print() |
0 commit comments