Kevin De Baerdemaeker

Stack

Modified 2023-06-25

A stack is a queue, but backwards as it uses Last In, First Out and is thus also constraint implementation of a linked list.

Typescript

export default class Stack<T> {
    public length: number;
    private head: Node<T> | undefined

    constructor() {
        this.head = undefined
        this.length = 0
    }

    push(item: T): void {
        this.length++
        if (!this.head) {
            this.head = { value: item, prev: undefined }
        } else {
            const newNode = { value: item, prev: this.head }
            this.head = newNode
        }
    }

    pop(): T | undefined {
        if (!this.head) return undefined
        this.length--;

        const head = this.head
        this.head = head.prev

        // free memory in certain languages
        return head.value
    }

    peek(): T | undefined {
        return this.head?.value
    }
}

References


Backlinks