My C++ iteration code


  • 0
    S
    ListNode* swapPairs(ListNode* head) {
        if (NULL== head || NULL==head->next){
            return head;
        }
        ListNode* headRec = head->next;
        
        ListNode* pre = head;
        while (NULL!=head && NULL!=head->next){
            ListNode* pair = head->next;
            ListNode* nextHead = pair->next;
                  
           // swap nodes
            pair->next = head;
            head->next = nextHead;
            
            // skip the first rotation, to set the connection between last pair and current pair
            if (pre!=head){
                pre->next = pair;
            }                  
            
            // change records for next rotation
            pre = head;
            head = nextHead;
        }
        
        return headRec;
    }

Log in to reply
 

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