Program in Python to reverse stack using recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #Recursive function to insert at bottom of the stack def insertatbottom(stack,item): if isempty(stack): push(stack,item) else: temp=pop(stack) insertatbottom(stack,item) push(stack,temp) #Recursive function to reverse stack using insertatbottom def reverse(stack): if not isempty(stack): temp=pop(stack) reverse(stack) insertatbottom(stack,temp) #function to create a stack.It intializes stack size as 0 def createstack(): stack=[] return stack #Function to check if stack is empty def isempty(stack): return len(stack)==0: #function to push an element onto the stack def push(stack,item): stack.append(item) #Function to pop an element from the stack def pop(stack): if isempty(stack): return -1 return stack.pop() #Function to print the stack def prints(stack): for i in range(len(stack)-1, -1, -1): print(stack[i], end = ' ') print() # Driver program to test above functions stack = createstack() push( stack, str(4) ) push( stack, str(3) ) push( stack, str(2) ) push( stack, str(1) ) print("Original Stack ") prints(stack) reverse(stack) print("Reversed Stack ") prints(stack) |