본문 바로가기
Algorithm/LEET CODE ( 파이썬 알고리즘 인터뷰)

[LEET CODE] 232. Implement Queue using Stacks

by newnu 2021. 3. 26.
반응형

# Problem

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

Notes:

  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

Follow-up: Can you implement the queue 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.

Constraints:

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, peek, and empty.
  • All the calls to pop and peek are valid.

 

# My Answer

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.s = []
        self.q=[]

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.q=[]
        if self.s ==[]: # s가 비어있으면 그냥 s에 추가
            self.s.append(x)
        else: # 이미 s에 값이 있으면, s 앞에 값을 추가
            self.q.append(x)
            self.s = self.q+self.s

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        a = self.s.pop()
        return a
    
    def peek(self) -> int:
        """
        Get the front element.
        """
        return self.s[-1]

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return len(self.s)==0

 

# Solution 1 - 스택 2개 사용

class MyQueue:
    def __init__(self):
        self.input = []
        self.output = []

    def push(self, x):
        self.input.append(x)

    def pop(self):
        self.peek()
        return self.output.pop()

    def peek(self):
        # output이 없으면 모두 재입력 #output에 값이 있으면 output에서 먼저 들어온 값 반환
        if not self.output:
            while self.input:
                self.output.append(self.input.pop())
        return self.output[-1]

    def empty(self):
        return self.input == [] and self.output == []

 

반응형