Skip to content

Commit b07254e

Browse files
committed
Implement Stack using Queues
1 parent 048399d commit b07254e

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/implement-stack-using-queues/
3+
4+
Implement the following operations of a stack using queues.
5+
push(x) -- Push element x onto stack.
6+
pop() -- Removes the element on top of the stack.
7+
top() -- Get the top element.
8+
empty() -- Return whether the stack is empty.
9+
10+
Example:
11+
MyStack stack = new MyStack();
12+
13+
stack.push(1);
14+
stack.push(2);
15+
stack.top(); // returns 2
16+
stack.pop(); // returns 2
17+
stack.empty(); // returns false
18+
19+
Notes:
20+
You must use only standard operations of a queue -- which means only push to back,
21+
peek/pop from front, size, and is empty operations are valid.
22+
Depending on your language, queue may not be supported natively.
23+
You may simulate a queue by using a list or deque (double-ended queue),
24+
as long as you use only standard operations of a queue.
25+
You may assume that all operations are valid
26+
(for example, no pop or top operations will be called on an empty stack).
27+
"""
28+
# Time Complexity: Push - O(n), Pop, Top, Empty - O(1)
29+
class MyStack:
30+
31+
def __init__(self):
32+
"""
33+
Initialize your data structure here.
34+
"""
35+
self.q = []
36+
37+
38+
def push(self, x: int) -> None:
39+
"""
40+
Push element x onto stack.
41+
"""
42+
self.q.append(x)
43+
for i in range(len(self.q)-1):
44+
self.q.append(self.q.pop(0))
45+
46+
47+
def pop(self) -> int:
48+
"""
49+
Removes the element on top of the stack and returns that element.
50+
"""
51+
return self.q.pop(0)
52+
53+
54+
def top(self) -> int:
55+
"""
56+
Get the top element.
57+
"""
58+
return self.q[0]
59+
60+
61+
def empty(self) -> bool:
62+
"""
63+
Returns whether the stack is empty.
64+
"""
65+
return not self.q
66+
67+
68+
69+
# Your MyStack object will be instantiated and called as such:
70+
# obj = MyStack()
71+
# obj.push(x)
72+
# param_2 = obj.pop()
73+
# param_3 = obj.top()
74+
# param_4 = obj.empty()

0 commit comments

Comments
 (0)