Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

stack operations using array container method.

 class Stack {

  constructor() {

    this.items = [];

  }

 

  // Pushes an element onto the stack

  push(element) {

    this.items.push(element);

  }

 

  // Pops an element from the stack

  pop() {

    if (this.items.length == 0) {

      return "Underflow";

    }

    return this.items.pop();

  }

 

  // Returns the top element of the stack

  peek() {

    if (this.items.length == 0) {

      return "No elements in Stack";

    }

    return this.items[this.items.length - 1];

  }

 

  // Returns true if the stack is empty, false otherwise

  isEmpty() {

    return this.items.length == 0;

  }

 

  // Prints the elements of the stack

  printStack() {

    let str = "";

    for (let i = 0; i < this.items.length; i++) {

      str += this.items[i] + " ";

    }

    return str;

  }

}

 

// Testing the stack implementation

let stack = new Stack();

console.log(stack.isEmpty()); // true

 

stack.push(10);

stack.push(20);

stack.push(30);

 

console.log(stack.printStack());

 

console.log(stack.peek());

 

console.log(stack.pop());

 

console.log(stack.printStack());

 

Output:-

10 20 30

30

30

10 20

Post a Comment

0 Comments

Ad Code

Responsive Advertisement