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.
思路:快慢指针,边遍历边交换顺序
代码:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode *pre=NULL;
ListNode *p=head;
ListNode *q=head;
if(head==NULL || head->next==NULL || m==n)
{
return head;
}
int step=1;
while(step<m)
{
pre=p;
p=p->next;
++step;
}
q=p;
ListNode *previous=q;
q=q->next;
ListNode *latter=q->next;
while(step<n)
{
q->next=previous;
previous=q;
q=latter;
if(q!=NULL)
{
latter=q->next;
}
++step;
}
if(pre!=NULL)
{
pre->next=previous;
}
else
{
head=previous;
}
p->next=q;
return head;
}