我有一个关于在Python中使用递归的概念怀疑。 以下是用于仅使用递归的反转堆栈的Python代码,我从this page at geeksforgeeks中复制了该代码。在python递归
# Below is a recursive function that inserts an element
# at the bottom of a stack.
def insertAtBottom(stack, item):
if isEmpty(stack):
push(stack, item)
else:
temp = pop(stack)
insertAtBottom(stack, item)
push(stack, temp)
# Below is the function that reverses the given stack
# using insertAtBottom()
def reverse(stack):
if not isEmpty(stack):
temp = pop(stack)
reverse(stack)
insertAtBottom(stack, temp)
好像reverse
使用stack
为全局变量,因为被调用的函数没有返回任何新的值调用函数的功能。这不是实现递归的错误方式吗?我们不应该避免在堆栈中使用全局变量吗?
另外,我们如何编辑这个函数,使被调用函数的每个实例都使用它自己的副本stack
?
请尝试打断你的句子*“我希望...的功能”*。这是一个令人头疼的问题。 –
'stack'不是全局的,它被传入函数。 –