Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,039 questions

52,004 answers

573 users

How to implement stack in Node.js

1 Answer

0 votes
class Stack {
    constructor() {
        this.items = [];
    }
      
    add(element) {
        return this.items.push(element);
    }
      
    size() {
        return this.items.length;
    }
      
    pop() {
        if (this.items.length > 0) {
            return this.items.pop();
        }
    }
      
    peek() {
        return this.items[this.items.length - 1];
    }
  
    isEmpty() {
        return this.items.length == 0;
    }
       
    print() {
        for (let i = 0; i < this.items.length; i++) {
            console.log(this.items[i]);
        }
    }
  
    delete() {
        this.items = [];
    }
}
  
let stack = new Stack();
  
stack.add(5);
stack.add(4);
stack.add(8);
stack.add(7);
stack.add(9);
stack.add(0);
  
console.log(stack.items);
  
stack.pop();
console.log(stack.items);
  
console.log(stack.peek());
  
console.log("size: " + stack.size());
  
console.log(stack.isEmpty());
  
stack.pop();
stack.print();
  
stack.delete();
console.log(stack.items);
  
  
  
  
/*
run:
  
[ 5, 4, 8, 7, 9, 0 ]
[ 5, 4, 8, 7, 9 ]
9
size: 5
false
5
4
8
7
[]
  
*/

 



answered Jan 28, 2022 by avibootz
edited Jan 28, 2022 by avibootz

Related questions

1 answer 60 views
1 answer 61 views
1 answer 99 views
1 answer 104 views
1 answer 91 views
...