Solution in C++ with O(1) space


  • 0
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if (!head) return NULL;
            if (!head->next) return head;
            
            ListNode* newHead = head->next;
            ListNode* first = head;
            ListNode* second = head->next;
            ListNode* hold = NULL;
            
            while (true){
                //swap
                first->next = second->next;
                second->next = first;
                if (hold != NULL) hold->next = second;            
                //increment
                hold = first;
                if (first->next && first->next->next){
                    first = first->next;
                    second = first->next;
                }
                else{
                    break;
                }
            }
            
            return newHead;
        }
    };
    

Log in to reply
 

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