LeetCode【92】Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

相比翻转整个链表稍微麻烦了那么一点,不过只要考虑好翻转的具体实现,问题都一样。AC代码如下:

    ListNode* reverse(ListNode* head,int len) {
        if(head == NULL || len<=0)
            return head;
        ListNode *first =head;
        ListNode *wait = head->next;
        ListNode *wait_next = NULL; 
        first->next= NULL;
        for(;wait!=NULL,len>0;--len)
        {
            wait_next = wait->next;
            wait->next = head;
            head = wait;
            wait = wait_next;
        }
        if(len>0)
            return head;
        else
        {
            first->next = wait;
            return head;
        }
    }
    
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(head ==NULL || m>=n)
            return head;
        if(m==1)
            return reverse(head,n-m);
        ListNode* h=head;
        ListNode* fir=head;
        int len=n-m;
        while(m>1)
        {
            fir=h;
            h=h->next;
            if(h==NULL)
                return head;
            m=m-1;
        }
        //第m个节点在链表中,且h指向该节点
        fir->next=reverse(h,len);
        return head;
    }

 

原文地址:https://www.cnblogs.com/ww-jin/p/4487051.html