Quick actions

cmd+k|ctrl+k

Navigation

Languages

Stack

Snippet info

Language

JavaScript

Visibility

public

Author

vinnysantos559

Created

2019-11-19T01:55:31Z

Updated

2019-11-19T02:12:25Z

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class Stack {
    constructor() {
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }
    
    push(value) {
        const newNode = new Node(value);
        if( this.length === 0) {
            this.top = newNode;
            this.bottom = newNode;
        }
        else {
            newNode.next = this.top;
            this.top = newNode;
        }
        this.length++;
    }
    
    peek() {
        return this.top;
    }
    
    pop() {
        if(this.length === 0) {
            return null;
        }
        if(this.top === this.bottom) {
            this.bottom = null;
        }
        const top = this.top;
        this.top = top.next;
        this.length--;
        return top;
    }
    
    isEmpty() {
        return (this.length === 0) ? true : false;
    }
}

const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack);
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.peek());
console.log(stack.isEmpty());
console.log(stack.pop());
console.log(stack.isEmpty());
console.log(stack);
console.log(stack.pop());
INFO