leetcode-Reverse Linked List II

来源:互联网 发布:知花作品全集 编辑:程序博客网 时间:2024/06/06 00:45

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn 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;
    }

0 0
原创粉丝点击