My C++ solution in 4ms using two pointers


  • 0
    C
    /*
    * The idea is using tempNode to point to the every first swap node, such as a,c for list a->b->c->d, then
    * loop.
    * The variable once here is help head pointer point to the correct head of the list.
    */
    
    class Solution {
    public:
        ListNode *swapPairs(ListNode *head) {
            ListNode *reverseList=head;
            ListNode *tempNode=NULL;
            int once=1;
            while(reverseList){
                if(reverseList->next==NULL)
                    break;
                tempNode=reverseList->next;
                reverseList->next=reverseList->next->next;
                tempNode->next=reverseList;
                if(once){
                    head=tempNode;
                    once=0;
                }
                tempNode=reverseList->next;
                if(reverseList->next&&reverseList->next->next){
                    reverseList->next=reverseList->next->next;
                }
                reverseList=tempNode;
            }
            return head;
        }
    };

Log in to reply
 

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