-
Notifications
You must be signed in to change notification settings - Fork 77
/
queue.py
64 lines (49 loc) · 1.4 KB
/
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
"""
Execution: python queue.py < input.txt
% more tobe.txt
to be or not to - be - - that - - - is
% python queue.py < tobe.txt
to be or not to be (2 left on queue)
"""
from algs4.utils.linklist import Node, LinkIterator
class Queue:
def __init__(self):
self.first = None
self.last = None
self.n = 0
def __str__(self):
return " ".join(i for i in self)
def __iter__(self):
return LinkIterator(self.first)
def size(self):
return self.n
def is_empty(self):
return self.first is None
def enqueue(self, item):
oldlast = self.last
self.last = Node(item, None)
if self.is_empty():
self.first = self.last
else:
oldlast.next = self.last
self.n += 1
def dequeue(self):
if self.is_empty():
raise ValueError("Queue empty")
else:
item = self.first.item
self.first = self.first.next
if self.is_empty():
self.last = None
self.n -= 1
return item
if __name__ == '__main__':
import sys
for line in sys.stdin:
queue = Queue()
for item in line.split():
if item != "-":
queue.enqueue(item)
elif not queue.is_empty():
print(queue.dequeue() + " ", end='')
print("(%d left on queue)" % queue.size())