[Leetcode] 232. Implement Queue using Stacks

2021. 1. 18. 12:28Problem Solving/LeetCode

Leetcode 232

(3) Implement Queue using Stacks - LeetCode

 

Implement Queue using Stacks - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Solution

class MyQueue:

    def __init__(self):
        self.stack = []

    def push(self, x: int) -> None:
        self.stack.append(x)

    def pop(self) -> int:
        front = self.stack[0]
        self.stack = self.stack[1:]
        return front

    def peek(self) -> int:
        return self.stack[0]

    def empty(self) -> bool:
        return len(self.stack) == 0


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

슬라이싱 해서 pop() 구현했다.
파이썬이 아닌 다른 언어였다면, 스택을 두개 사용 해야 했을 것이다.

반응형