Solution Review: Reverse a Stack
This review provides a detailed analysis of the solution to reverse a stack using recursion.
We'll cover the following...
Solution: Using Recursion
Python 3.5
Files
import stack as sdef insertAtBottom(stack, item) : # Recursive function that inserts an element at the bottom of a stack.# Base caseif s.isEmpty(stack) :s.push(stack, item)# Recursive caseelse:temp = s.pop(stack)insertAtBottom(stack, item)s.push(stack, temp)def reverse(testVariable) :# Recursive caseif not s.isEmpty(testVariable) :temp = s.pop(testVariable)reverse(testVariable)insertAtBottom(testVariable, temp)# Driver CodemyStack = s.createStack()s.push(myStack, str(8))s.push(myStack, str(5))s.push(myStack, str(3))s.push(myStack, str(2))print("Original Stack")s.printStack(myStack)reverse(myStack)print("\n\nReversed Stack")s.printStack(myStack)
Explanation
A simple solution to reversing a stack is to create another stack. Pop elements from the old stack into the new stack and we will ...