/**
* 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) {
ListNode*ahead=new ListNode(-1);
ahead->next=head;
ListNode*p1=ahead;
ListNode*p2=head;
for(int i=1;i<m;i++)
p1=p1->next;
for(int i=1;i<n;i++)
p2=p2->next;
ListNode*p3=p2->next;
p2->next=NULL;
p1->next=reverse(p1->next);
ListNode*q=p1->next;
while(q->next)q=q->next;
q->next=p3;
return ahead->next;
}
ListNode* reverse(ListNode* head) {
ListNode*rhead=NULL;
ListNode*p=head;
ListNode*pre=NULL;
while(p)
{
ListNode*pnext=p->next;
if(pnext==NULL)rhead=p;
p->next=pre;
pre=p;
p=pnext;
}
return rhead;
}
};
部分翻转链表Reverse Linked List II
最新推荐文章于 2020-07-21 11:19:21 发布