My accepted C++ Non-Recursive Code (Only change the pointer)


  • 0
    N
    • When the number of the original list is Odd Number, the last node
      should not be swapped
    • When the number of the original list is Even Number, the last node
      should be swapped

    ListNode *swapPairs(ListNode *head) {
        if(head == NULL || head->next == NULL)
            return head;
            
        ListNode *pre = head;
        ListNode *cur = pre->next;
        ListNode *nxt = cur->next;
        head = cur;
        
        while(nxt != NULL) {
            if(nxt->next == NULL) {
                cur->next = pre;
                pre->next = nxt;
                return head;
            }
            else {
                cur->next = pre;
                pre->next = nxt->next;
                
                pre = nxt;
                cur = nxt->next;
                nxt = cur->next;
            }
        }
        
        cur->next = pre;
        pre->next = nxt;
        return head;
    }

Log in to reply
 

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