Not able to push all elements of a stack into another stack using for loop in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

As we know the stack works on the principle of Last in first out. At first, to insert into another stack you need to pop() all elements from the first stack and push into the second stack.

Example

var myFirstStack=[10,20,30,40,50,60,70];
var mySecondStack=[];
for(;myFirstStack.length;){
   mySecondStack.push(myFirstStack.pop());
}
console.log("After popping the all elements from the first stack=");
console.log(myFirstStack);
console.log("After pushing (inserting) all the elements into the second
stack=");
console.log(mySecondStack);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo189.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo189.js
After popping the all elements from the first stack=
[]
After pushing (inserting) all the elements into the second stack=
[
   70, 60, 50, 40,
   30, 20, 10
]
raja
Published on 14-Sep-2020 08:20:02
Advertisements