w3resource

JavaScript Exercises: Top and bottom elements of a stack

JavaScript Stack: Exercise-10 with Solution

Top & Bottom of Stack

Write a JavaScript program to find the top and bottom elements of a given 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() {
    if (this.isEmpty())
      return "No elements in Stack";
    return this.items[this.items.length - 1];
  }

  isEmpty() {
    return this.items.length === 0;
  }
  get_Top() {
    return this.items[this.items.length - 1];
  }
  get_Bottom() {
    return this.items[0];
  }
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(6);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(7); 
console.log(stack.displayStack(stack));
console.log("Top element of the stack is:", stack.get_Top());
console.log("Bottom element of the stack is:", stack.get_Bottom());

Sample Output:

"Initialize a stack:"
"Input some elements on the stack:"
"Stack elements are:"
"1 6 3 2 5 7"
"Top element of the stack is:"
7
"Bottom element of the stack is:"
1 

Flowchart:

Flowchart: JavaScript  Exercises: Top and bottom elements of a stack .
Flowchart: JavaScript  Exercises: Top and bottom elements of a stack.

Live Demo:

* To run the code mouse over on Result panel and click on 'RERUN' button.*

Live Demo:

See the Pen javascript-common-editor by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that retrieves both the top and bottom elements of a stack without modifying it.
  • Write a JavaScript function that implements peek operations for both the first and last elements in an array-based stack.
  • Write a JavaScript function that returns an object with properties for the top and bottom elements of a stack.
  • Write a JavaScript function that validates the stack before attempting to access its top and bottom elements and handles underflow gracefully.

Improve this sample solution and post your code through Disqus

Stack Previous: Remove duplicates from a given stack .
Stack Exercises Next: Rotate the stack elements to the left.

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.