Swap Nodes in Pairs in TypeScript

function swapPairs(head: ListNode | null): ListNode | null {
    // A dummy node to simplify the handling of edge cases
    let dummy = new ListNode(0);
    dummy.next = head;

    // Current node starts from the dummy
    let current: ListNode | null = dummy;

    while (current.next !== null && current.next.next !== null) {
        // Nodes to be swapped
        let first: ListNode = current.next;
        let second: ListNode = current.next.next;

        // Swapping
        first.next = second.next;
        second.next = first;
        current.next = second;

        // Moving to the next pair
        current = first;
    }

    // Return the new head of the list
    return dummy.next;
}

PrevNext