Leetcode brushing record-232. Using the stack to implement the queue

Insert picture description here

Reference question 225

class MyQueue:

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


    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.
        """
        
        self.stack = self.stack[::-1]
        res = self.stack.pop(-1)
        self.stack = self.stack[::-1]
        return res
    def peek(self) -> int:
        """
        Get the front element.
        """
        self.stack = self.stack[::-1]
        res = self.stack.pop(-1)
        self.stack.append(res)
        self.stack = self.stack[::-1]
        return res


    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return not bool(self.stack)



# 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()
Published 43 original articles · praised 14 · 20,000+ views

Guess you like

Origin blog.csdn.net/weixin_41545780/article/details/105463176