/**
* 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(head==NULL || head->next==NULL)
return head;
ListNode *newHead = new ListNode(-1);
newHead->next = head;
ListNode* begin=head;
ListNode* preBegin=newHead;
ListNode* end=newHead;
ListNode* postEnd=head;
while(--m)
{
preBegin=preBegin->next;
begin=begin->next;
}
while(n--)
{
postEnd=postEnd->next;
end=end->next;
}
reverse(begin,end);
preBegin->next=begin;
end->next=postEnd;
return newHead->next;
}
void reverse(ListNode*& begin, ListNode*& end)
{
if(begin == end)
return;
else if(begin->next == end)
end->next = begin;
else
{//at least 3 nodes
ListNode* pre = begin;
ListNode* cur = pre->next;
ListNode* post = cur->next;
while(post != end->next)
{
cur->next = pre;
pre = cur;
cur = post;
post = post->next;
}
cur->next = pre;
}
//swap
ListNode* temp = begin;
begin = end;
end = temp;
}
};
Reverse Linked List II
最新推荐文章于 2022-10-08 18:10:16 发布