My accepted C++ code without recursion and using constant memory.


  • 0
    F

    The idea is simple: swap the first pair and then proceed to the next pair, until next pair do not have enough nodes.

    ListNode* swapPairs(ListNode* head) {
          if (head == nullptr or head->next == nullptr){
                return head;
            }
            
            ListNode dummy(-1);
            ListNode* prev = &dummy;
            prev->next = head;
    
            ListNode* node1 = head;
            ListNode* node2 = head->next;
    
            while (node1 != nullptr and node2 != nullptr){
                
                ListNode* next = node2->next;
                prev->next = node2;
                node2->next = node1;
                node1->next = next;
                prev = node1;
                node1 = next;
    
                if (next != nullptr){
                    node2 = next->next;
                }
                else{
                    break;
                }
            }
    
            return dummy.next;
        }
    

Log in to reply
 

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