(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.

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤ length of list.

 

题目要求:

这是对反转链表的一个变形,简单的反转链表实现可以参考http://www.cnblogs.com/AndyJee/p/4461502.html

反转部分链表(将第m个结点到第n个结点间的元素翻转)

注意点:

in-place原地,即不开辟额外的结点空间

one-pass一次遍历

解题思路:

1、找到第m个结点,找到第n个结点,通过指针保存第m-1个结点和第n+1个结点;

2、将第m个结点和第n个结点间的元素反转;

3、将1~m、m~n、n~length三部分连接起来,这里需要考虑m是否等于1,即是否为头结点。如果是,需将head指向第n个结点;

4、返回head结点指针。

参考代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(head==NULL || head->next==NULL)
            return head;
            
        ListNode *prev=head;
        ListNode *curr=head;
        ListNode *next=head;
        
        ListNode *mPrev=NULL;
        ListNode *mTh=NULL;
        ListNode *nTh=NULL;
        ListNode *nNext=NULL;
        
        for(int i=1;curr!=NULL;i++){
            next=curr->next;
            if(i==m){
                mPrev=prev;
                mTh=curr;
            }
            if(i>m && i<=n)
                curr->next=prev;
            if(i==n){
                nTh=curr;
                nNext=next;
            }
            prev=curr;
            curr=next;
        }
        
        if(m==1){
            mTh->next=nNext;
            head=nTh;
        }
        else{
            mPrev->next=nTh;
            mTh->next=nNext;
        }
        
        return head;
    }
};
原文地址:https://www.cnblogs.com/AndyJee/p/4461672.html