JavaScript Exercises: Swap the top two elements of a stack
JavaScript Stack: Exercise-15 with Solution
Swap Top Two Elements
Write a JavaScript program to swap the top two elements of a given stack.
Sample Solution:
JavaScript Code:
Sample Output:
Stack elements are: 1 2 3 4 5 6 7 Swap top two elements: Stack elements are: 1 2 3 4 5 7 6 Input two more elements on the stack: Stack elements are: 1 2 3 4 5 7 6 8 9 Swap top two elements: Stack elements are: 1 2 3 4 5 7 6 9 8
Flowchart:



Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that swaps the top two elements of a stack and returns the modified stack.
- Write a JavaScript function that performs the swap operation using array destructuring without a temporary variable.
- Write a JavaScript function that checks if the stack has at least two elements before attempting to swap.
- Write a JavaScript function that logs the stack state before and after swapping the top two elements.
Improve this sample solution and post your code through Disqus
Stack Previous: Remove a specific element from a stack.
Stack Exercises Next: Nth element from the top of the stack.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics