Merge Two Sorted Lists in TypeScript

function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
    // Create a dummy head to simplify the merging process
    let dummy = new ListNode();
    let current = dummy;

    // Iterate while both lists have elements
    while (list1 !== null && list2 !== null) {
        if (list1.val < list2.val) {
            current.next = list1;
            list1 = list1.next;
        } else {
            current.next = list2;
            list2 = list2.next;
        }
        current = current.next;
    }

    // Append the remaining elements of list1 or list2
    current.next = list1 !== null ? list1 : list2;

    // The merged list starts from dummy's next node
    return dummy.next;
}

PrevNext