/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode *reverse(ListNode *head,ListNode *tail)
{
if(head==tail)
return head;
ListNode *curhead=head;
ListNode *scan=head->next;
head->next=NULL;
while(scan!=tail)
{
ListNode *temp=scan->next;
scan->next=curhead;
curhead=scan;
scan=temp;
}
tail->next=curhead;
return tail;
}
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(!head)return head;
ListNode *prehead=new ListNode(-1);
prehead->next=head;
int count=1;//记录当前扫描的节点下表
ListNode *prem=NULL;
ListNode *postn=NULL;
ListNode *scan=head;
ListNode *prescan=prehead;
ListNode *postscan=head->next;
ListNode *mposition=NULL;
ListNode *nposition=NULL;
while(scan)
{
if(count==m)
{
prem=prescan;
mposition=scan;
}
if(count==n)
{
nposition=scan;
postn=postscan;
break;
}
prescan=scan;
scan=scan->next;
if(!scan)break;
postscan=scan->next;
count++;
}
prem->next=reverse(mposition,nposition);
mposition->next=postn;
return prehead->next;
}
};
92. Reverse Linked List II
最新推荐文章于 2022-10-08 18:10:16 发布