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

在这里插入图片描述

参考题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()
发布了43 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/105463176