- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Not able to push all elements of a stack into another stack using for loop in JavaScript?
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 ]
Advertisements