[Leetcode] - 225

Jisung Park·2021년 5월 10일
0
  • 두개의 queue를 사용해 stack을 구현하시오

  • 두가지 방식으로 구현 가능함
    - push: O(1), pop: O(N)
    - push: O(N), pop: O(1)



from collections import deque

class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.left = deque([])
        self.right = deque([])        

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.right.append(x)
        

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        while len(self.right) > 1:
            self.left.append(self.right.popleft())
        ret = self.right.popleft()
        
        self.right = self.left
        self.left = deque([])
        return ret

    def top(self) -> int:
        """
        Get the top element.
        """
        while len(self.right) > 1:
            self.left.append(self.right.popleft())
        ret = self.right.popleft()
        self.left.append(ret)
        
        self.right = self.left
        self.left = deque([])
        return ret
        

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


# 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()

0개의 댓글