225 큐를 이용한 스택 구현

1 minute read

큐를 이용한 스택 구현

문제

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

생각

코드

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.

Updated: