My 26 lines code in C. 0 ms.


  • 0
    X
    struct ListNode* swapPairs(struct ListNode* head) {
        struct ListNode *cur = head;
        struct ListNode *prev, *next;
        struct ListNode *temp;
        struct ListNode store;
        if (head == NULL) return NULL;
        prev = &store;
        int i = 0;
        int d;
        while(cur) {
            if ((d = i%2) == 0) {
                next = cur;
                cur = cur->next;
                next->next = NULL;
            } else {
                prev->next = cur;
                temp = cur->next;
                cur->next = next;
                prev = next;
                cur = temp;
            }
            i++;
        }
        if (d == 0) prev->next = next;
        return store.next;
    }

Log in to reply
 

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