4ms Easy C++ Iterative Solution


  • 2

    Well, since the head pointer may also been modified, we create a new_head that points to it to facilitate the swapping process.

    For the example list 1 -> 2 -> 3 -> 4 in the problem statement, it will become 0 -> 1 -> 2 -> 3 -> 4 (we init new_head -> val to be 0). Then we set a pointer pre to new_head and another cur to head. Each time, we will swap pre -> next and cur -> next using the following piece of code.

    pre -> next = cur -> next;
    cur -> next = cur -> next -> next;
    pre -> next -> next = cur;
    

    After swapping them, we update as follows:

    pre = cur; 
    cur = pre -> next; 
    

    to swap the next two nodes.

    Finally, we return new_head -> next.

    The complete code is as follows.

    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) { 
            if (!head || !(head -> next)) return head;
            ListNode* new_head = new ListNode(0);
            new_head -> next = head;
            ListNode* pre = new_head; 
            ListNode* cur = head;
            while (pre -> next && cur -> next) {
                pre -> next = cur -> next;
                cur -> next = cur -> next -> next;
                pre -> next -> next = cur;
                pre = cur;
                cur = pre -> next;
            }
            return new_head -> next;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.