使用2个堆栈创建队列

时间:2020-02-02 19:32:46

标签: python-3.x algorithm data-structures

class Queue2Stacks(object):

    def __init__(self):

        # Two Stacks
        self.instack = []
        self.outstack = []

    def enqueue(self,element):

        # Add an enqueue with the "IN" stack
        self.instack.append(element)

    def dequeue(self):
        if not self.outstack:
            while self.instack:
                # Add the elements to the outstack to reverse the order when called
                self.outstack.append(self.instack.pop())
        return self.outstack.pop()

有人可以帮我理解这个问题吗?我真的不明白if.self.outstack是否在这里工作。我以为self.outstack以一个空列表开头,为什么会触发该语句?我也不太了解self.instack,self.instack是我们从入队函数追加的列表,对吗?什么会破坏while循环?

2 个答案:

答案 0 :(得分:0)

更好地理解循环结构可能会对这段代码有所帮助。 这是资源:http://openbookproject.net/thinkcs/python/english3e/conditionals.html

  if not (apples >= 5): 
     print("You have a few apples only.")

与以下内容类似:

  if (apples <= 5):
     print("You have a few apples only.") 

通过了解“ not”(而不是“!”),逻辑门会更深一些。操作员。希望能帮助您理解代码。

答案 1 :(得分:0)

您引用的if条件:

if not self.outstack:

...表示“如果堆栈是空的”。这是必需的,因为预期的操作是从该堆栈中弹出一个值(请参见return语句)。现在,如果那里什么也没有,我们不能仅仅抛出一个“抱歉,什么都没有了”的异常,因为另一个堆栈中可能仍然有值:instack。因此,在这种情况下,我们需要从那个堆栈返回一个值:我们需要返回的值位于instack bottom 处。因此,我们需要从该堆栈中弹出所有 值,并将它们附加到outstack上,这实际上将它们按相反的顺序放置:位于{{1}底部的值},最终将在instack的顶部,这正是我们想要的,因为我们会将那个元素作为返回值弹出。

outstack条件说:“虽然while中仍有值”。这是必需的,因为我们希望从该堆栈中弹出所有所有值。