-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPriorityQueue.py
71 lines (60 loc) · 1.43 KB
/
PriorityQueue.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class PriorityQueueNode:
def __init__(self, value, pr):
self.data = value
self.priority = pr
self.next = None
# Implementation of Priority Queue
class PriorityQueue:
def __init__(self):
self.front = None
def isEmpty(self):
return True if self.front == None else False
def push(self, value, priority):
if self.isEmpty() == True:
self.front = PriorityQueueNode(value,priority)
return 1
else:
if self.front.priority > priority:
newNode = PriorityQueueNode(value,priority)
newNode.next = self.front
self.front = newNode
return 1
else:
temp = self.front
while temp.next:
if priority <= temp.next.priority:
break
temp = temp.next
newNode = PriorityQueueNode(value,priority)
newNode.next = temp.next
temp.next = newNode
return 1
def pop(self):
if self.isEmpty() == True:
return
else:
self.front = self.front.next
return 1
def peek(self):
if self.isEmpty() == True:
return
else:
return self.front.data
def traverse(self):
if self.isEmpty() == True:
return "Queue is Empty!"
else:
temp = self.front
while temp:
print(temp.data, end = " ")
temp = temp.next
# Driver code
if __name__ == "__main__":
# 7 -> 4 -> 5 -> 6
pq = PriorityQueue()
pq.push(4, 1)
pq.push(5, 2)
pq.push(6, 3)
pq.push(7, 0)
pq.traverse()
pq.pop()