[Algorithm] LeetCode #225 - Implement Stack Using Queues
개요
LeetCode #225, Implement Stack Using Queues 문제를 풀어봅니다.
Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push
, top
, pop
, and empty
).
Implement the MyStack
class:
void push(int x)
Pushes element x to the top of the stack.int pop()
Removes the element on the top of the stack and returns it.int top()
Returns the element on the top of the stack.boolean empty()
Returnstrue
if the stack is empty,false
otherwise.
Notes:
- You must use only standard operations of a queue, which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue), as long as you use only a queue’s standard operations.
Example 1:
Input [“MyStack”, “push”, “push”, “top”, “pop”, “empty”] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false]
Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False
Constraints:
1 <= x <= 9
- At most
100
calls will be made topush
,pop
,top
, andempty
. - All the calls to
pop
andtop
are valid.
Follow-up: Can you implement the stack such that each operation is amortized O(1)
time complexity? In other words, performing n
operations will take overall O(n)
time even if one of those operations may take longer. You can use more than two queues.
Queue로 stack을 구현합니다. Queue 선언은 deque로 합니다. push()는 append로 오른쪽에 넣어준 후에 넣은 것 직전까지의 범위에서 왼쪽부터 값을 하나씩 빼서 오른쪽으로 넣어줍니다. 그렇게 하면 방금 들어간 것이 제일 왼쪽으로 가게 됩니다. pop은 stack이니까 LIFO를 만들어야 하고 (Queue는 FIFO) 나중에 들어간 것이 왼쪽에 있으니까 왼쪽 것을 빼 주면 됩니다. top도 맨 처음 것을 빼 옵니다. 비었는지는 길이로 체크합니다.
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q = collections.deque()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.q.append(x)
for _ in range(len(self.q)-1):
self.q.append(self.q.popleft())
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.q.popleft()
def top(self) -> int:
"""
Get the top element.
"""
return self.q[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return len(self.q) == 0