w3resource

JavaScript Exercises: Rotate the stack elements to the right

JavaScript Stack: Exercise-12 with Solution

Rotate Stack Right

Write a JavaScript program to rotate the stack elements to the right direction.

Sample Solution:

JavaScript Code:

class Stack {
  constructor() {
    this.items = [];
  }

  push(element) {
    this.items.push(element);
  }

  pop() {
    if (this.isEmpty())
      return "Underflow";
    return this.items.pop();
  }

  peek() {
    if (this.isEmpty())
      return "No elements in Stack";
    return this.items[this.items.length - 1];
  }

  isEmpty() {
    return this.items.length === 0;
  }

 rotateLeft() {
    if (this.isEmpty()) {
      return "Underflow";
    }
    let firstElement = this.items.shift();
    this.items.push(firstElement);
    return this.items;
  }
displayStack(stack) {
  console.log("Stack elements are:");
  let str = "";
  for (let i = 0; i < stack.items.length; i++)
    str += stack.items[i] + " ";
  return str.trim();
 }        
}
console.log("Initialize a stack:")
let stack = new Stack();
console.log("Input some elements on the stack:")
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
console.log(stack.displayStack(stack));
console.log("Rotate the stack elements to the left:")
console.log(stack.rotateLeft());
console.log("Again rotate the stack elements to the left:")
console.log(stack.rotateLeft());
console.log("Again rotate the stack elements to the left:")
console.log(stack.rotateLeft());

Sample Output:

Initialize a stack:
Input some elements on the stack:
Stack elements are:
1 2 3 4 5
Rotate the stack elements to the right:
[5,1,2,3,4]
Again rotate the stack elements to the right:
[4,5,1,2,3]
Again rotate the stack elements to the right:
[3,4,5,1,2]

Flowchart:

Flowchart: JavaScript  Exercises: Rotate the stack elements to the right .
Flowchart: JavaScript  Exercises: Rotate the stack elements to the right.
Flowchart: JavaScript  Exercises: Rotate the stack elements to the right.

Live Demo:

See the Pen javascript-stack-exercise-12 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that rotates the elements of a stack to the right by one position using pop and unshift operations.
  • Write a JavaScript function that rotates a stack right by n positions and returns the resulting stack.
  • Write a JavaScript function that implements right rotation using a temporary array to store the last element.
  • Write a JavaScript function that validates the rotation process by checking the final order against expected outcomes.

Go to:


PREV : Rotate Stack Left.
NEXT : Remove Specific Element from Stack.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.