Leetcode刷题记录——232. 用栈实现队列

Leetcode刷题记录——232. 用栈实现队列_第1张图片

参考题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()

你可能感兴趣的:(leetcode,python编程技巧)