Untitled

 avatar
unknown
plain_text
7 days ago
1.2 kB
3
Indexable
public ListNode swapPairs(ListNode head) {
    // Create a dummy node to handle edge cases
    ListNode dummy = new ListNode(-1);
    dummy.next = head; // Dummy node points to the original head

    ListNode prev = dummy; // Tracks the end of the previous pair
    ListNode temp = head;  // Tracks the current node (head of the current pair)

    // Loop as long as there are at least two nodes to swap
    while (temp != null && temp.next != null) {
        // Identify the two nodes to swap
        ListNode firstNode = temp;        // The first node in the pair
        ListNode secondNode = temp.next; // The second node in the pair

        // Perform the swapping
        firstNode.next = secondNode.next; // First node points to the node after the second
        secondNode.next = firstNode;      // Second node points to the first node
        prev.next = secondNode;           // Connect the previous node to the second node

        // Move pointers for the next pair
        prev = firstNode;  // First node is now the end of the swapped pair
        temp = firstNode.next; // Move temp to the next pair's first node
    }

    return dummy.next; // Return the new head
}
Leave a Comment