C clear and easy way,not value-moving (I use an empty head node)


  • 0
    P
    struct ListNode* swapPairs(struct ListNode* head) {
        struct ListNode *tmp, list;
        list.next = head;
        head = &list;
        
        while(head->next&&head->next->next) {
            tmp = head->next;
            head->next = tmp->next;
            tmp->next = head->next->next;
            head->next->next = tmp;
            head = head->next->next;
        }
        
        return list.next;
    }

Log in to reply
 

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