How to use Temporary Stack In Javascript
In this approach, we initialize a temporary stack. We will pop all elements from the original stack and push all of them into the temporary stack and also we will push the new element to the temporary stack. Now one by one we will pop all elements from the temporary stack and push them to the original stack.
Example: In this example, we use an additional stack to insert an element at the bottom of the stack.
function insertBottom(stack, newEle) {
let tempStack = [];
while (stack.length > 0) {
tempStack.push(stack.pop());
}
stack.push(newEle);
while (tempStack.length > 0) {
stack.push(tempStack.pop());
}
}
let stack = [4, 6, 8, 10];
let newEle = 2;
console.log("Stack before insertion:", stack);
insertBottom(stack, newEle);
console.log("Stack after insertion:", stack);
Output
Stack before insertion: [ 4, 6, 8, 10 ] Stack after insertion: [ 2, 4, 6, 8, 10 ]
Time Complexity: O(N)
Auxiliary Space: O(N)
JavaScript Program to Insert an Element at oBttom of the Stack
Given a stack and an element, our task is to insert the element at the bottom of the stack in JavaScript.
Example:
Input:
Initial Stack: [1, 2, 3, 4]
N= 5
Output:
Final Stack: [5, 1, 2, 3, 4]
Below are the approaches to inserting an element at the bottom of the stack:
Table of Content
- Using Temporary Stack
- Using Recursion