w3resource

JavaScript Exercises: Nth element from the top of the stack

JavaScript Stack: Exercise-16 with Solution

Write a JavaScript program to get the nth element from the top of the stack.

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() {
    return this.items[this.items.length - 1];
  }
  isEmpty() {
    return this.items.length === 0;
  }
  size() {
    return this.items.length;
  }
getNthFromTop(n) {
    if (this.items.length < n) {
      return "Index out of range";
    }
    return this.items[this.items.length - n];
  }  
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();
 }      
}
let stack = new Stack();
stack.push(100);
stack.push(200);
stack.push(300);
stack.push(400);
stack.push(500);
stack.push(600);
stack.push(700);
console.log(stack.displayStack(stack));
n = 2;
console.log("nth element from the top of the stack where n = "+n);
console.log(stack.getNthFromTop(n));
n = 5;
console.log("nth element from the top of the stack where n = "+n);
console.log(stack.getNthFromTop(n));
n = 7;
console.log("nth element from the top of the stack where n = "+n);
console.log(stack.getNthFromTop(n));

Sample Output:

Stack elements are:
100 200 300 400 500 600 700
nth element from the top of the stack where n = 2
600
nth element from the top of the stack where n = 5
300
nth element from the top of the stack where n = 7
100

Flowchart:

Flowchart: JavaScript  Exercises: Nth element from the top of the stack.
Flowchart: JavaScript  Exercises: Nth element from the top of the stack.
Flowchart: JavaScript  Exercises: Nth element from the top of the stack.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Stack Previous: Swap the top two elements of a stack.
Stack Exercises Next: Nth element from the bottom of the stack.

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.