forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoQueuedStack.py
71 lines (64 loc) · 1.62 KB
/
TwoQueuedStack.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
67
68
69
70
71
class StackUsingQueues:
def __init__(self) -> None:
"""
Initializing the stack using two queues.
>>> stack = StackUsingQueues()
"""
self.queue1 = []
self.queue2 = []
def push(self, item: int) -> None:
"""
Push an item onto the stack.
>>> stack = StackUsingQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.push(3)
>>> stack.peek()
3
"""
while len(self.queue1) != 0:
self.queue2.append(self.queue1[0])
self.queue1.pop(0)
self.queue1.append(item)
while len(self.queue2) != 0:
self.queue1.append(self.queue2[0])
self.queue2.pop(0)
def pop(self) -> int:
"""
Pop the top item from the stack and return it.
>>> stack = StackUsingQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.pop()
2
>>> stack.pop()
1
>>> stack.pop()
0
"""
if len(self.queue1) != 0:
popped = self.queue1.pop(0)
return popped
else:
return 0
def peek(self) -> int:
"""
Return the top item from the stack without removing it.
>>> stack = StackUsingQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.peek()
2
>>> stack.pop()
2
>>> stack.peek()
1
>>> stack.pop()
1
>>> stack.peek()
0
"""
if len(self.queue1) != 0:
return self.queue1[0]
else:
return 0