leetcode 225. 用队列实现栈(python)

在这里插入图片描述
题解:

  1. 对于队列,是先进先出;对于栈,是先进后出,两者在元素出去的位置地方正好相反,因此我们需要用队列实现后进元素先出去的效果;
    乍一想,我们需要实现队列内元素的反转操作,
    但是此题的解题思想并没有完全实现反转,只是把队列的最后一个元素,移动到队头即可;这样就可以实现和栈相同的效果(后进先出);
  2. 即我们需要实现队头元素为栈底元素。

方法一:我们首选利用双队列来进行实现:
基本思想如下:
在队列的入队过程中实现:(假设当前入队元素为x)

  1. 我们利用两个队列queue和help来实现;queue是主队列,help是辅助队列;
  2. 对于queue我们一直出队元素,直到为空,其中出队的元素按序装进help队列中;
  3. 然后queue此时为空,我们再进队当前需要入队的元素x,因为此时queue为空,所以当前进队元素x就变成了队头(对于栈来说,就是栈底的那个元素);并且此时在队列中会优先出队,因此我们相当于实现了栈的后进先出。
  4. 之后再从help队列中把元素再复制进来即可。
    代码如下:
class MyStack:

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


    def push(self, x):
        """
        Push element x onto stack.
        """

        while len(self.queue) > 0:

            self.help.append(self.queue.pop(0))

        self.queue.append(x)

        while len(self.help) > 0:

            self.queue.append(self.help.pop(0))

    def pop(self) :
        """
        Removes the element on top of the stack and returns that element.
        """

        de = self.queue.pop(0)
        return de

    def top(self):
        """
        Get the top element.
        """
        de = self.queue[0]
        return de

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        if len(self.queue) == 0:
            return True
        return False

方法二:单队列实现:
基本思想

  1. 在队列中push过程中实现;
  2. 首先在队列中进入当前元素x;
  3. 然后获取当前队列的长度length;
  4. 最后把队列按照顺序出队,出队的元素再重新进入当前队列,每出队一个元素,length的值减少一;直到length的长度为1,不再出队;此时队列的头元素就是元素x;这样在pop的过程中就实现了后进先出的效果。

代码如下:

class MyStack:

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

    def push(self, x):
        """
        Push element x onto stack.
        """

        self.queue.append(x)

        length = len(self.queue)

        while length > 1:

            self.queue.append(self.queue.pop(0))
            length -= 1


    def pop(self) :
        """
        Removes the element on top of the stack and returns that element.
        """

        de = self.queue.pop(0)
        return de



    def top(self):
        """
        Get the top element.
        """
        de = self.queue[0]
        return de

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        if len(self.queue) == 0:
            return True
        return False
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值