Share C++ code easy to understand


  • 0
    L
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) 
        {
            if(!head)return head;
            ListNode *pre=head,*after=0,*m_th=0,*n_th=0;
            pre=N_th_list(head,m-1);
            after=N_th_list(head,n+1);
            m_th=N_th_list(head,m);
            n_th=N_th_list(head,n);
            n_th->next=nullptr;
            m_th=reverselist(m_th);
    		if (pre)
    			pre->next = m_th;
    		if(1==m)
            {
              N_th_list(n_th,n)->next=after;
              return n_th;
            }
            
            else
            N_th_list(head,n)->next=after;
            return head;
        }
    private:
       ListNode* N_th_list(ListNode *head,int m)
        {
            if(!m)return nullptr;
            while(--m)
            {
                head=head->next;
            }
            return head;
        }
         ListNode* reverselist(ListNode* head) 
         {
             if(!head)return nullptr;
             ListNode *pre=nullptr,*cur=head,*next=head->next;
             while(cur)
             {
                 next=cur->next;
                 cur->next=pre;
                 pre=cur;
                 cur=next;
             }
             return pre;
             
         }
        
        
    };

Log in to reply
 

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