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 ≤ m ≤ n ≤ length of list.
/**
* 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) {
ListNode *cur=head;
ListNode *pre=NULL;
if(head==NULL||head->next==NULL)
{
/*空结点或者只有一个结点*/
return head;
}
for(int i=1;i<m;i++)
{
pre=cur;
cur=cur->next;
}
ListNode *end=cur;/*end是第m-1结点*/
ListNode *new_node=cur;/*new_node是第m结点*/
cur=cur->next;
for(int j=m;j<n;j++)
{/*生成逆转的子链表*/
ListNode *next=cur->next;/*复制*/
cur->next=new_node;/*断链*/
new_node=cur;/*更新*/
cur=next;/*移步*/
}
end->next=cur;/*cur此时是第n个结点*/
if(pre)
pre->next=new_node;/*new)node是逆转链表的头结点*/
else
head=new_node;
return head;
}
};