I have a conceptual doubt about using recursion in python. Below is the python code for reversing a stack using only recursion which I have copied from this page at geeksforgeeks.
# 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)
It seems like the function reverse is using stack as a global variable because the called function isn't returning any new value to the caller function. Isn't this a wrong way of implementing recursion? Shouldn't we avoid using global variables in stack?
Also, how would we edit this function such that each instance of the called function uses it's own copy of stack?
stackis not global, it's being passed into the function.