...

/

Solution Review: Reverse a Stack

Solution Review: Reverse a Stack

This review provides a detailed analysis of the solution to reverse a stack using recursion.

Solution: Using Recursion

Press + to interact
index.js
stack.js
import Stack from './stack.js'
function insertAtBottom(stack, item) { // Creating a helper function
// Base case
if (stack.isEmpty() == true) {
stack.push(item);
}
// Recursive case
else {
var temp = stack.pop();
insertAtBottom(stack, item);
stack.push(temp);
}
}
function reverse(testVariable) {
// Recursive case
if (testVariable.isEmpty() == false) {
var temp = testVariable.pop();
reverse(testVariable);
insertAtBottom(testVariable, temp);
}
}
myStack = new Stack();
myStack.push(2);
myStack.push(3);
myStack.push(5);
myStack.push(8); // <---- 8 will be at the top of the stack because it was pushed last
console.log("Original Stack: ");
console.log(myStack.getStack());
reverse(myStack);
console.log("Reversed Stack: ");
console.log(myStack.getStack());

Explanation

A simple solution to reversing a stack is to create another stack. Pop elements from the ...

Access this course and 1400+ top-rated courses and projects.