Short accepted cpp solutions


  • -1
    T
        void swapPair(ListNode *head)
        {
            ListNode *tmp1 = head->next;
            head->next = tmp1->next;
            tmp1->next = tmp1->next->next;
            head->next->next = tmp1;
        }
        ListNode *swapPairs(ListNode *head) {
            ListNode res(0);
            res.next = head;
            for(ListNode *it = &res; it->next && it->next->next;  it = it->next->next)
                swapPair(it);
            return res.next;
        }

  • 0
    T

    Recursive Version:

    ListNode *swapPairs(ListNode *head) {
            if(NULL == head || NULL == head->next) return head;
            ListNode *res = head->next;
            head->next = swapPairs(res->next);
            res->next = head;
            return res;
     }

Log in to reply
 

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