码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-232-用栈实现队列

时间:2019-10-05 20:17:19      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:tac   ack   initial   com   info   data   bsp   elf   ret   

题目描述:

技术图片

 

 

方法一:双栈

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import deque
        self.stack = deque()

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        tmp_stack = []
        while self.stack:
            tmp_stack.append(self.stack.pop())
        self.stack.append(x)
        while tmp_stack:
            self.stack.append(tmp_stack.pop())

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if self.stack: return self.stack.pop()

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

    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-232-用栈实现队列

标签:tac   ack   initial   com   info   data   bsp   elf   ret   

原文地址:https://www.cnblogs.com/oldby/p/11625398.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!