forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamic_queue.py
66 lines (55 loc) · 1.39 KB
/
dynamic_queue.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
class Node:
def __init__(self, key: int) -> None:
self.key = key
self.next = None
class DynamicQueue:
def __init__(self) -> None:
self.__begin = None
self.__end = None
def is_empty(self) -> bool:
return self.__begin is None
def enqueue(self, val: int) -> None:
node = Node(val)
if self.is_empty():
self.__begin = node
else:
self.__end.next = node
self.__end = node
def dequeue(self) -> Node:
if self.is_empty():
return None
node = self.__begin
self.__begin = self.__begin.next
if self.is_empty():
self.__end = None
return node
def show(self) -> None:
curr = self.__begin
while curr:
print(f"[{curr.key}]->", end="")
curr = curr.next
print()
def size(self) -> int:
size, curr = 0, self.__begin
while curr:
size += 1
curr = curr.next
return size
def main():
queue = DynamicQueue()
queue.enqueue(10)
queue.enqueue(15)
queue.enqueue(42)
queue.enqueue(70)
queue.show()
print("size: ", queue.size())
print()
queue.dequeue()
queue.show()
print("size: ", queue.size())
print()
queue.dequeue()
queue.show()
print("size: ", queue.size())
if __name__ == "__main__":
main()