My c++ solution, use two pointers and iteration

  • 1
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
        ListNode *fake = new ListNode(0);
        fake->next = head;
        ListNode* p1 = fake, *p2 = fake->next;
        while(p2 && p2->next){
            ListNode* pre = p1; //record the node before the pair
            p1 = p1->next;
            p2 = p2->next;
            ListNode* after = p2->next; //record the node after the pair
            /*swap the pair*/
            pre->next = p2;
            p2->next = p1;
            p1->next = after;
            p2 = after; //p2 goes to the node after p1 and start over again
        return fake->next;

Log in to reply

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