[LeetCode] Implement Stack using Queues (Python)
2024. 3. 8. 10:54ㆍ알고리즘
from collections import deque
class MyStack:
def __init__(self):
self.stack1 = deque()
self.stack2 = deque()
def push(self, x: int) -> None:
self.stack1.append(x)
def pop(self) -> int:
while len(self.stack1) > 1:
temp = self.stack1.popleft()
self.stack2.append(temp)
if len(self.stack1) == 1:
answer = self.stack1.popleft()
self.stack1, self.stack2 = self.stack2, self.stack1
return answer
def top(self) -> int:
return self.stack1[-1]
def empty(self) -> bool:
return False if self.stack1 else True
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
'알고리즘' 카테고리의 다른 글
[LeetCode] Flood Fill (Python) (0) | 2024.03.09 |
---|---|
[LeetCode] Decode String (Python) (0) | 2024.03.08 |
[LeetCode] Implement Queue using Stacks (Python) (0) | 2024.03.08 |
[LeetCode] Binary Tree Inorder Traversal (Python) (0) | 2024.03.07 |
[LeetCode] Clone Graph (Python) (0) | 2024.03.07 |