My clear c++ solution


  • 0
    Z
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
     
    typedef ListNode* ListNodePtr;
    
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNodePtr withHead = new ListNode(0); 
            withHead->next = head;
            ListNodePtr bf = withHead, first = NULL, second = NULL, lt = NULL;
            while((first = bf->next) && (second = bf->next->next)) {  // neither first nor second is NULL
                // swap first and second
                lt = second->next;
                bf->next = second;
                second->next = first;
                first->next = lt;
                
                // move bf foreward
                bf = first;
            }
            
            return withHead->next;
        }
    };

Log in to reply
 

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