Quick actions

cmd+k|ctrl+k

Navigation

Languages

Stack (LinkedList based) in JavaScript

Snippet info

Language

JavaScript

Visibility

public

Author

patrykstachowiak

Created

2025-03-08T10:08:40.444569Z

Updated

2025-03-08T10:32:38.210569Z

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;
    }

    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++;
        return this;
    }

    pop() {
        if (this.top === null) return;
        if (this.length === 1) {
            this.top = null;
            this.bottom = null;
        } else {
            const nodeToRemove = this.top;
            this.top = nodeToRemove.next;
        }
        this.length--;
    }

    //isEmpty
}

const myStack = new Stack();
myStack.push("Albert");
myStack.push("Dominik");
myStack.push("Alfred");
myStack.push("Kinga");
myStack.push("Monika");

console.log(myStack);
console.log(myStack.peek().value);
console.log(myStack.pop());
console.log(myStack.peek().value);
INFO