-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue_linked.py
62 lines (51 loc) · 1.46 KB
/
queue_linked.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
class Queue:
def __init__(self):
self.logical_size = 0
self.first = None
self.last = None
def is_empty(self):
return self.logical_size == 0
def __len__(self):
return self.logical_size
def enqueue(self,value):
new_node = Node(value)
if self.logical_size == 0:
self.first = new_node
else:
self.last.next = new_node
self.last = new_node
self.logical_size += 1
def dequeue(self):
if self.logical_size == 0:
raise EmptyQueue("Can't dequeue from an empty queue.")
elif self.logical_size == 1:
self.last = None
return_value = self.first.value
self.first = self.first.next
self.logical_size -= 1
return return_value
def __str__(self):
output = "Queue->"
next_node = self.first
while next_node is not None:
output += str(next_node.value)
output += "->"
next_node = next_node.next
return output
class Node:
def __init__(self,value):
self.value = value
self.next = None
class EmptyQueue(Exception):
pass
if __name__ == "__main__":
my_queue = Queue()
for c in "ABCDEFG":
my_queue.enqueue(c)
for c in "HIJKLMN":
print(my_queue.dequeue())
print(len(my_queue))
my_queue.enqueue(c)
while True:
print(my_queue.dequeue())
print(len(my_queue))