-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path225_Implement_Stack_using_Queues.py
More file actions
44 lines (37 loc) · 985 Bytes
/
225_Implement_Stack_using_Queues.py
File metadata and controls
44 lines (37 loc) · 985 Bytes
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
"""
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
"""
from collections import deque
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = deque([])
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.stack.append(x)
for _ in range(len(self.stack) - 1): #KEY: range = len(stack) - 1
self.stack.append(self.stack.popleft())
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.stack.popleft()
def top(self) -> int:
"""
Get the top element.
"""
return self.stack[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return len(self.stack) == 0