C Solution - Simple Iterative


  • 0
    P
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* swapPairs(struct ListNode* head) {
        if(!head || !head->next) return head;
        
        struct ListNode dummy;
        dummy.next = head;
        struct ListNode * prev = &dummy;
        struct ListNode * cur = head;
        struct ListNode * next = head->next;
        
        while (next && cur)
        {
            prev->next = cur->next;
            cur->next = next->next;
            next->next = cur;
            prev = cur;
            cur = cur->next;
            if (cur)    next = cur->next;
        }
        
        return dummy.next;
        
    }
    

Log in to reply
 

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