-
Notifications
You must be signed in to change notification settings - Fork 64
/
3_5_myqueue.py
53 lines (41 loc) · 1.12 KB
/
3_5_myqueue.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
#!/usr/bin/env python
"""
Implement a queue with two stacks in the MyQueue class.
This should never be used, though -- the deque data structure from the
standard library collections module should be used instead.
"""
class MyQueue(object):
def __init__(self):
self.first = []
self.second = []
def size(self):
return len(self.first) + len(self.second)
def add(self, number):
self.first.append(number)
def peek(self):
first = self.first
second = self.second
if len(second):
return second[-1]
while len(first):
second.append(first.pop())
return second[-1]
def remove(self):
first = self.first
second = self.second
if len(second):
return second.pop()
while len(first):
second.append(first.pop())
return second.pop()
def main():
queue = MyQueue()
queue.add(1)
queue.add(2)
queue.add(3)
print queue.size() # 3
print queue.peek() # 1
print queue.remove() # 1
print queue.peek() # 2
if __name__ == '__main__':
main()