/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n)
{
ListNode*p=head;
ListNode*q=head;
ListNode*x=head;
ListNode*y=head;
int count=1;
if(m==1)
{
while(p && count<n)
{
p=p->next;
count++;
}
while(q!=p)
{
x=q;
q=q->next;
if(p->next==NULL)
{
p->next=x;
x->next=NULL;
}
else
{
x->next=p->next;
p->next=x;
}
}
return p;
}
else
{
while(p && count<n)
{
if(count==m-1)
{
q=p;
}
count++;
p=p->next;
}
x=q->next;
while(x!=p)
{
y=x;
x=x->next;
q->next=y->next;
if(p->next==NULL)
{
p->next=y;
y->next=NULL;
}
else
{
y->next=p->next;
p->next=y;
}
}
}
return head;
}
};



京公网安备 11010502036488号