Share my 14 lines C++ solution


  • 43
    H
     ListNode *reverseBetween(ListNode *head, int m, int n) {
        if(m==n)return head;
    	n-=m;
        ListNode prehead(0);
        prehead.next=head;
        ListNode* pre=&prehead;
        while(--m)pre=pre->next;        
        ListNode* pstart=pre->next;
        while(n--)
        {
            ListNode *p=pstart->next;
            pstart->next=p->next;
            p->next=pre->next;
            pre->next=p;
        }
        return prehead.next;
    }

  • 0
    D

    Nice hack of adding a prehead to neutralize m=1 case.


  • 0

    Nice code! In fact, the following line is not needed. You've handled it in a unified manner :-)

    if(m==n)return head;

  • 1
    _

    my solution

    modified above code, using pointer to pointer, not to create a prehead.


Log in to reply
 

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