Simple iterative solution 3ms


  • 0
    M

    The following iterative code works by swapping 2 adjacent nodes. Sanity check is handled at the while loop.

    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) 
        {
            ListNode* it = head;
            int temp;
            while(it != NULL && it -> next != NULL)
            {
                temp = it -> val;
                it -> val = it -> next -> val;
                it -> next -> val = temp;
    
                it = it -> next -> next;
            }
            return head;
        }
    };
    

  • 0
    E

    It seems you are modifying the value of each node. Please node in the question "You may not modify the values in the list, only nodes itself can be changed."


Log in to reply
 

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