Reverse Nodes in k-Group in TypeScript

function reverseKGroup(head: ListNode | null, k: number): ListNode | null {
    // Helper function to reverse a part of the linked list.
    const reverseLinkedList = (start: ListNode | null, end: ListNode | null): ListNode | null => {
        let prev: ListNode | null = null, curr = start;
        while (curr !== end) {
            const nextTemp: ListNode | null = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    };

    // Dummy node to handle edge cases easily.
    const dummy = new ListNode(0);
    dummy.next = head;
    let prevGroupEnd: ListNode = dummy;

    while (true) {
        let kthNode: ListNode | null = prevGroupEnd;
        // Find the kth node from the current position.
        for (let i = 0; i < k; i++) {
            if (kthNode === null) break;
            kthNode = kthNode.next;
        }
        if (kthNode === null) return dummy.next; // Return the new head of the list.

        // Mark the end of the next group.
        const nextGroupStart: ListNode | null = kthNode.next;

        // Reverse the current group.
        const newGroupStart = reverseLinkedList(prevGroupEnd.next, nextGroupStart);

        // Connect the reversed group with the rest of the list.
        const temp: ListNode | null = prevGroupEnd.next;
        prevGroupEnd.next = newGroupStart;
        prevGroupEnd = temp;

        // Set the next node for traversal.
        prevGroupEnd.next = nextGroupStart;
    }
}

PrevNext