反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseBetween(struct ListNode* head, int m, int n)
{
struct ListNode* pre=(struct ListNode*)malloc(sizeof(struct ListNode));
pre->val=-1;
pre->next=head;
int count=0;
m++;
n++;
struct ListNode* tmp=pre;
struct ListNode* start=NULL;
struct ListNode* pcur=NULL;
struct ListNode* last=NULL;
struct ListNode* p2=NULL;
while(tmp)
{
count++;
if(count==m-1)
{
start=tmp;
pcur=start->next;
}
if(count==n)
{
p2=tmp;
last=p2->next;
p2->next=NULL;
break;
}
tmp=tmp->next;
}
struct ListNode* pnext=NULL;
struct ListNode* pnew=last;
while(pcur)
{
pnext=pcur->next;
pcur->next=pnew;
pnew=pcur;
pcur=pnext;
}
start->next=pnew;
return pre->next;
}
C++
/**
* 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(NULL==head || NULL==head->next)
{
return head;
}
ListNode* pnew=NULL;
ListNode* p=head;
ListNode* pnext=NULL;
ListNode* first_last=NULL;
int k=1;
while(k<m)
{
first_last=p;
p=p->next;
k++;
}
ListNode* second_last=p;
while(k<=n)
{
pnext=p->next;
p->next=pnew;
pnew=p;
p=pnext;
k++;
}
second_last->next=p;
if(first_last)
{
first_last->next=pnew;
return head;
}
return pnew;
}
};
python
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
pre=ListNode(-1)
pre.next=head
m+=1
n+=1
tmp=pre
count=0
while tmp:
count+=1
if count==m-1:
start=tmp
pcur=start.next
if count==n:
last=tmp
pnew=last.next
last.next=None
break
tmp=tmp.next
while pcur:
pnext=pcur.next
pcur.next=pnew
pnew=pcur
pcur=pnext
start.next=pnew
return pre.next