Quick actions

cmd+k|ctrl+k

Navigation

Languages

Stack_linked_list

Snippet info

Language

JavaScript

Visibility

public

Author

varun.muriyanat

Created

2025-05-01T20:11:36.131037Z

Updated

2025-05-01T22:26:47.799523Z

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

class Stack {
    constructor() {
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }
    
    peek() {
        return this.top.value;
    }
    
    push(value) {
        let node = new Node(value);
        if (this.length === 0) {
            this.top = node;
            this.bottom = node;
            this.length++;
            return this;
        }
        
        node.next = this.top;
        this.top = node;
        this.length++;
        return this;
    }
    
    pop() {
        if (this.length === 0) {
            return null;
        }
        
        if (this.length === 1) {
            let val = this.top.value;
            this.top = null;
            this.bottom = null;
            this.length = 0;
            return val;
        }
        
        let val = this.top.value;
        let next = this.top.next;
        this.top = next;
        this.length--;
        return val;
    }
    
    isEmpty() {
        return (this.length === 0);
        
    }
    
    // print the elements in the stack
    printList() {
        const values = [];
        let node = this.top;
        while (node !== null) {
            values.push(node.value);
            node = node.next;
        }
        console.log(values.join(" | "));
    }
}

const myStack = new Stack();
console.log(myStack.isEmpty());
myStack.push(10);
myStack.push(20);
myStack.push(30);
myStack.push(40);
console.log(myStack.peek());
myStack.printList();
console.log(myStack.pop());
myStack.printList();
console.log(myStack.isEmpty());
console.log(myStack.length);
console.log(myStack);
INFO