【问题标题】:Trouble understanding pop() when implementing Queue using Stacks使用堆栈实现队列时无法理解 pop()
【发布时间】:2020-06-29 21:14:09
【问题描述】:

这是一个 leetcode 问题。完整问题在这里:https://leetcode.com/problems/implement-queue-using-stacks/solution/

这是完整的解决方案。

class MyQueue:
    def __init__(self):
        self.s1 = []
        self.s2 = []

    def push(self, x):
        #Time complexity = O(1)
        #Space complexity = O(1)

        self.s1.append(x)

    def pop(self):
        #Time complexity = O(n)
        #Space complexity = O(n)
        self.peek()
        return self.s2.pop()

    def peek(self):
        #Time complexity = O(1)
        #space complexity = O(1)

        if self.s2 == []: #if s2 is empty
            while self.s1 != []: #while s1 is not empty
                self.s2.append(self.s1.pop()) #s2 takes in all the s1 values | i don't understand this line???
        return self.s2[-1]        

    def empty(self):
        #Time complexity = O(1)
        #Space complexity = O(1)
        return self.s1 == [] and self.s2 == []

代码运行良好,但我不明白这一行:

self.s2.append(self.s1.pop())

这是来自这个函数:

    def peek(self):

        if self.s2 == []: #if s2 is empty
            while self.s1 != []: #while s1 is not empty
                self.s2.append(self.s1.pop()) #s2 takes in all the s1 values
        return self.s2[-1]    

我正在尝试按照代码进行操作,但不明白 self.s1.pop() 实际上如何返回任何内容?

另外,self.s1.pop()self.pop() 的功能有何不同

提前非常感谢!

【问题讨论】:

    标签: python recursion stack queue


    【解决方案1】:

    function pop() 假设从堆栈中删除顶部元素并同时返回删除的值,返回时它将把返回并从 s1 堆栈顶部删除的任何内容放入 s2 堆栈的顶部。

    【讨论】:

    • 谢谢!我太愚蠢了,完全忘记了列表的内置 python pop 函数。谢谢!
    • 没关系!有时,即使是最简单的问题,我们也会感到困惑。祝你好运
    【解决方案2】:

    好的,对不起,伙计们。我深入研究了实际的自定义 pop 函数,以至于我完全忘记了 python 内置的 pop() 函数用于列表!解决了!

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 2014-08-12
      • 2014-12-23
      • 2010-10-15
      • 1970-01-01
      • 2016-01-08
      • 2013-06-10
      • 1970-01-01
      • 2015-05-15
      相关资源
      最近更新 更多