Description:
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.
反转指定的一部分链表,从第m个节点到第n个节点部分的链表要被反转,其中会满足1 ≤ m ≤ n ≤ length of list
Solution:
1、首先是需要找到第m个节点,并且需要保存第m个节点的上一个节点
2、找到之后就开始翻转,直到将第n个节点也翻转完,并且要保存第n个节点之后的下一个节点。
3、之后将第m个节点的上一个节点(如果没有,则它为head)指向n,将m指向n节点的下一个。
Code:
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* pre=NULL;//the pre node of mth node
int count=0;
ListNode* temp=head;
while(temp)
{
count++;
if(count==m)
break;
pre=temp;
temp=temp->next;
}
ListNode* mthnode=temp;
ListNode* pre1=temp;
temp=temp->next;
while(count!=n)
{
ListNode* t1=temp->next;
temp->next=pre1;//transver
pre1=temp;
temp=t1;
count++;
}
if(pre)
pre->next=pre1;
else
head=pre1;
mthnode->next=temp;
return head;
}
};