【发布时间】:2014-11-29 00:16:34
【问题描述】:
我编写了一个快速的 Python 函数来反转堆栈的内容。
def ReverseStack(input_stack):
oldStack = input_stack
newStack = Stack()
while not oldStack.isEmpty():
item = oldStack.pop()
newStack.push(item)
return newStack
s = Stack()
s.push('hello')
s.push('world')
s.push('I')
s.push('live')
s.push('underwater')
new = ReverseStack(s)
print "\nOriginal stack..."
while not s.isEmpty():
print s.pop()
print "\nNew stack..."
while not new.isEmpty():
print new.pop()
但是,当我打印每个堆栈的内容(原始堆栈和反向堆栈)时,看起来好像原始堆栈的所有内容都已通过 pop 方法删除。这让我很困惑,因为我将它作为参数传递给了一个创建临时堆栈以将内容弹出的函数。我原以为这样会原封不动。
我的问题是为什么会发生这种情况,纠正它的最佳方法是什么?谢谢!
【问题讨论】:
标签: python function python-2.7 stack