/**
* 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||!head->next)
return head;
ListNode* rest=NULL;
ListNode* new_head=NULL;
ListNode* new_tail=NULL;
if(m==1)
{
new_tail=helper(head,1,n,new_head,rest);
new_tail->next=rest;
return new_head;
}
ListNode* curr=head;
for(int i=1;i<m-1;i++)
curr=curr->next;
new_tail=helper(curr->next,m,n,new_head,rest);
new_tail->next=rest;
curr->next=new_head;
return head;
}
ListNode* helper(ListNode *head, int curr, int n, ListNode*& new_head, ListNode*& rest)
{
if(curr==n)
{
rest=head->next;
new_head=head;
return head;
}
ListNode* p=helper(head->next,curr+1,n,new_head,rest);
p->next=head;
head->next=NULL;
return head;
}
};
leetcode 92: Reverse Linked List II
最新推荐文章于 2025-05-21 15:08:20 发布