CS기초/코딩테스트

LeetCode 232 (Easy) Implement Queue using Stacks

오늘의 나1 2021. 3. 23. 01:02
출처: leetcode.com/problems/implement-queue-using-stacks/
 

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

문제

한글 번역은 아래 더보기를 클릭해주세요.

풀이

class MyQueue:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack = list()

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.stack.append(x)

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

    def peek(self) -> int:
        """
        Get the front element.
        """
        return self.stack[0] if len(self.stack) > 0 else None

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        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()

결과