Kevin De Baerdemaeker

Queue

Modified 2023-06-25

The queue is a constraint version of a linked list, and is First In, First Out.

Typescript

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

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

    enqueue(item: T): void {
        const node = { value: item, next: undefined }

        this.length++
        if (!this.tail) {
            this.tail = this.head = node
        } else {
            this.tail.next = node
            this.tail = node
        }
    }

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

        const head = this.head
        this.head = this.head.next

        if (this.length === 0) {
            this.tail = undefined
        }

        // free memory if needed in other lang
        return head.value
    }

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

References


Backlinks