O(n) time/ O(1) space solution.


  • 0
    S

    ListNode* swap(ListNode **prev,ListNode *a, ListNode *b){

        if(b == NULL){
            return NULL;
        }
        ListNode *c = b->next;
        b->next = a;
        a->next = c;
        if(*(prev) != NULL){
            (*(prev))->next = b;
        }
        *prev = a;
        return c;
    }
    ListNode* swapPairs(ListNode* head) {
        
        if(head == NULL || head->next == NULL){
            return head;
        }
        ListNode *prev = NULL;
        ListNode *t_head = head->next;
        ListNode *t = swap(&prev,head,head->next);
        head = t_head;
        while(t){
            t = swap(&prev,t,t->next);
        }
        return head;
    }

Log in to reply
 

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