forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_using_two_queues.py
135 lines (110 loc) · 3.25 KB
/
stack_using_two_queues.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
from collections import deque
class StackUsingQueues:
def __init__(self):
self.queue1 = deque()
self.queue2 = deque()
def push(self, value: int) -> None:
"""
Pushes an element onto the stack.
Args:
value (int): The element to push onto the stack.
Example:
>>> stack = StackUsingQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.push(3)
"""
self.queue2.append(value)
while self.queue1:
self.queue2.append(self.queue1.popleft())
self.queue1, self.queue2 = self.queue2, self.queue1
def pop(self) -> None:
"""
Pops and removes the top element from the stack.
Example:
>>> stack = StackUsingQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.pop()
"""
if self.queue1:
self.queue1.popleft()
def top(self) -> int:
"""
Returns the top element of the stack without removing it.
Returns:
int: The top element of the stack.
Example:
>>> stack = StackUsingQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.top()
2
"""
if self.queue1:
return self.queue1[0]
return None
def size(self) -> int:
"""
Returns the current size (number of elements) of the stack.
Returns:
int: The size of the stack.
Example:
>>> stack = StackUsingQueues()
>>> stack.size()
0
>>> stack.push(1)
>>> stack.push(2)
>>> stack.push(3)
>>> stack.size()
3
>>> stack.pop()
>>> stack.size()
2
"""
return len(self.queue1)
def is_empty(self) -> bool:
"""
Checks if the stack is empty.
Returns:
bool: True if the stack is empty, False otherwise.
Example:
>>> stack = StackUsingQueues()
>>> stack.is_empty()
True
>>> stack.push(1)
>>> stack.is_empty()
False
"""
return len(self.queue1) == 0
def peek(self) -> int:
"""
Returns the top element of the stack without removing it.
Returns:
int: The top element of the stack.
Example:
>>> stack = StackUsingQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.peek()
2
"""
if self.queue1:
return self.queue1[0]
return None
if __name__ == "__main__":
stack = StackUsingQueues()
# Push some elements onto the stack
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack size:", stack.size())
print("Top element:", stack.top())
# Pop elements from the stack
stack.pop()
print("Top element after pop:", stack.top())
stack.pop()
print("Top element after another pop:", stack.top())
print("Is stack empty?", stack.is_empty())
print("Peek at the top element:", stack.peek())
print("Final stack size:", stack.size())