-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_linked_list.py
More file actions
86 lines (67 loc) · 2.21 KB
/
Copy pathqueue_linked_list.py
File metadata and controls
86 lines (67 loc) · 2.21 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
################################################################
# queue implementation using linked list
# methods implemented :
# enqueue (offer), dequeue(poll), peek, isFull, isEmpty, print
################################################################
from linked_list.list_node import ListNode
class QueueWithLinkedList:
def __init__(self, max_size):
self.max_size = max_size
self.size = 0
self.head = None
self.tail = None
def isEmpty(self) -> bool:
return not self.head
def isFull(self) -> bool:
return self.max_size == self.size
def enqueue(self, val) -> bool:
""" return false if queue is already full """
if self.isFull():
print("queue is full")
return False
""" create a new list node """
node = ListNode(val)
""" check if queue is empty
if true, then both head and tail will point to the same node
"""
if self.isEmpty():
self.head = self.tail = node
self.size = self.size + 1
return True
""" for an existing queue, point current tail to the new node
and move the tail pointer forward
increase the size of the queue
"""
self.tail.next = node
self.tail = self.tail.next
self.size = self.size + 1
return True
def dequeue(self) -> int:
""" return -1 if queue is empty """
if self.isEmpty():
print("queue is empty")
return -1
""" return value from top of the list and move
head pointer forward
"""
rval = self.head.val
self.head = self.head.next
self.size = self.size - 1
return rval
def peek(self) -> int:
if self.isEmpty():
print("queue is empty")
return -1
""" return the value from the beginning of the list """
return self.head.val
def print(self) -> None:
if self.isEmpty():
print("queue is empty")
return
out = ""
curr = self.head
while curr:
out = out + " " + str(curr.val)
curr = curr.next
print(out)
return