您的位置:首页 > 编程语言 > Go语言

Reverse Linked List II

2015-01-23 12:10 344 查看
/**
* 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(m==n)
{
return head;
}
m=m-1;
n=n-1;
ListNode* start=NULL;
ListNode* end=NULL;
ListNode* pre=NULL;
ListNode* cur=head;
ListNode* next=head->next;
for(int i=0;i<m;++i)
{
pre=cur;
cur=next;
next=next->next;
}
start=pre;
for(int i=0;i<(n-m);++i)
{
cur->next=pre;
pre=cur;
cur=next;
next=next->next;
}
end=cur->next;
cur->next=pre;
if(start==NULL)
{
head->next=end;
return cur;
}
else
{
start->next->next=end;
start->next=cur;
return head;
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm