Quick actions

cmd+k|ctrl+k

Navigation

Languages

Stacks

Snippet info

Language

JavaScript

Visibility

public

Author

arungohil10.ag

Created

2025-09-19T07:24:34.550125Z

Updated

2025-09-19T07:24:34.550125Z

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 newTop = new Node(value)
        if (this.length === 0) {
            this.top = newTop
            this.bottom = newTop
        } else {
            const holdingPointer = this.top
            this.top = newTop
            this.top.next = holdingPointer
        }
        this.length++
        return this
    }

    pop() {
        if (this.top === null) {
        return null
        }
        
        const poppedValue = this.top.value
        if (this.top.next !== null) {
            this.top = this.top.next
        } else {
            this.top = null
            this.bottom = null
        }
        this.length--
        return this
    }

    isEmpty() {
        if (this.length === 0) {
            return true
        } else {
            return false
        }
    }
    
    printStack() {
        let current = this.top
        while (current !== null) {
            console.log(current.value)
            current = current.next
        }
    }
}

const myStack = new Stack();
myStack.push("Google")
myStack.push("Udemy")
myStack.push("Youtube")
myStack.printStack()
myStack.pop()
myStack.printStack()
console.log(myStack.peek())
INFO