0%
November 8, 2024

Doubly-Linked List in Typescript

data-structure

class Node<T> {
    value: T;
    next: Node<T> | null = null;
    prev: Node<T> | null = null;

    constructor(value: T) {
        this.value = value;
    }

    appendRight(newNode: Node<T>): void {
        newNode.prev = this;
        newNode.next = this.next;
        if (this.next) {
            this.next.prev = newNode;
        }
        this.next = newNode;
    }

    appendLeft(newNode: Node<T>): void {
        newNode.next = this;
        newNode.prev = this.prev;
        if (this.prev) {
            this.prev.next = newNode;
        }
        this.prev = newNode;
    }

    traverse(): Node<T>[] {
        const head = this.getHead();
        const nodes: Node<T>[] = [];
        let current: Node<T> | null = head;

        while (current) {
            nodes.push(current);
            current = current.next;
        }

        return nodes;
    }

    getHead(): Node<T> {
        let current: Node<T> = this;

        while (current.prev) {
            current = current.prev;
        }

        return current;
    }
}