您的位置:首页 > 其它

部分翻转链表Reverse Linked List II

2017-05-16 14:15 543 查看
/**
* 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法