My accepted [5ms] solution in C++,Any advising?


  • 0
    K
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *swapPairs(ListNode *head) 
        {
            ListNode* pre=new ListNode(0);
            pre->next=head;
            ListNode* retHead=pre;
            ListNode* temp;
            for(ListNode* iter=head;(iter!=NULL)&&(iter->next!=NULL);iter=iter->next)
            {
               temp=iter->next->next;
               pre->next=iter->next;
               iter->next->next=iter;
               iter->next=temp;
               pre=iter;
            }
             return retHead->next;
        }
       
    };

  • 2
    G

    4ms.

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

  • 0
    D

    that's awesome


Log in to reply
 

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