题目
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.
翻转链的一部分。
保存:
1、需要翻转的开始位置
2、开始位置的前一个位置
向后推移,暂存下下个位置,将下个位置的next指向当前位置,不断后推直到结束。
把开始位置的前一个位置的next指向最后一个,将最后一个位置的next指向之后的位置。
特殊情况:
1、开始位置是头
2、结束位置是尾
代码:
/**
* 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(m==n)
return head;
ListNode *before=NULL,*begin=head,*pos=head,*next=head->next,*nn;
//交换位置之前的位置,开始位置,当前位置,下一位置,下一位置的下一位置
int count=1; //计数
while(count<m) //寻找开始位置
{
before=pos;
pos=pos->next;
begin=pos; //保存开始位置
next=pos->next;
count++;
}
while(count<n) //更改中间段的连接,使之反向
{
nn=next->next;
next->next=pos;
pos=next;
next=nn;
count++;
}
begin->next=next; //将原来的m位置与原来的n+1位置相连
if(before!=NULL) //将原的m-1位置与原来的n位置相连
before->next=pos;
else //如果之前没有,则修改头
head=pos;
return head;
}
};