How to implement a Stack using node js

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

  // Method to push an element onto the stack
  push(element) {
    this.items.push(element);
  }

  // Method to pop an element from the stack
  pop() {
    if (this.items.length === 0) {
      return 'Underflow';
    }
    return this.items.pop();
  }

  // Method to display the stack
  display() {
    console.log(this.items);
  }
}

// Example usage
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.display();

 

Post your Answer