w3resource

JavaScript Exercises: Remove all the elements from a given stack

JavaScript Stack: Exercise-6 with Solution

Clear Stack

Write a JavaScript program to remove all elements from 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;
  }
  clear() {
    this.items = [];
  }
 // Returns the number of elements in the stack
 size() {
    return this.items.length;
  }  

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("Is the stack empty?");
console.log(stack.isEmpty()); 
console.log("Input some elements on the stack:")
stack.push(1);
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(6); 
console.log(stack.displayStack(stack));
console.log("Remove all the elements from the said stack:")
stack.clear();
console.log("Is the stack empty?");
console.log(stack.isEmpty());

Sample Output:

Initialize a stack:
Is the stack empty?
true
Input some elements on the stack:
Stack elements are:
1 4 3 2 5 6
Remove all the elements from the said stack:
Is the stack empty?
true

Flowchart:

Flowchart: JavaScript  Exercises: Remove all the elements from a given stack.
Flowchart: JavaScript  Exercises: Remove all the elements from a given stack.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Stack Previous: Find the maximum element in a stack (using an array).
Stack Exercises Next: Count all the elements in a given stack.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/stack/javascript-stack-exercise-6.php