225 큐를 이용한 스택 구현
큐를 이용한 스택 구현
문제
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).
MyStack 클래스는
- push(int x): 스택 상단에 요소 삽입
- pop(): 스택 상단 요소 제거하고 그 요소 반환
- top(): 스택 상단 요소 반환
- empty(): 스택 비었는지 여부 반환
조건
- $1 \le x \le 9$
- At most 100 calls will be made to push, pop, top, and empty.
- All the calls to pop and top are valid.
예제
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
해결할 이슈?
- 큐를 이용한 스택 구현
- 스택의 기능?
- push: 삽입
- pop: 스택의 가장 상단 요소 제거하거 해당 요소를 반환
- top: 가장 상단의 요소
- empty: 스택이 비었는지 확인
1st
생각
- 큐를 이용하라고 했으니 python 자료구조에서 가능한 que를 사용
list
- 리스트도 비슷한 기능 제공하지만, 고정된 길이의 작업에 최적화되어 있고,
pop(0)
과insert(0, v)
에서 $O(n)$ 메모리 이동이 발생
deque
queqe
- queue 모듈의 LifoQueue를 사용해보자
- push?
- put 사용
- pop?
- get 사용
- top?
- LifoQueue에 top은 없다. 왜?
- queue 모듈에 있는 Queue 클래스는 동기화된 큐 클래스
- 동기화된 스택에서는 무엇이 top이고 언제 가득 차고 언제 비는지가 일정치 않을 수 있다
- 정 필요하다면 내부의 queue 리스트가 있으니 이를 활용
- LifoQueue에 top은 없다. 왜?
코드
from queue import LifoQueue
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.que = LifoQueue()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.que.put(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.que.get()
def top(self) -> int:
"""
Get the top element.
"""
return self.que.queue[-1]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return self.que.qsize() == 0
결과
Runtime: 32 ms, faster than 57.41% of Python3 online submissions for Implement Stack using Queues. Memory Usage: 14.4 MB, less than 48.18% of Python3 online submissions for Implement Stack using Queues.