头插法的变形体,被是否是从头结点开始绕晕了,想了半天如何区分都没想到直接用m的值判别就好了嘛~
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
//头插法,从m开始,插入n个即可
if(!head->next)//条件中注明结点个数至少为1,那么结点为1时,直接返回
return head;
int count,k;
k=n-m;//需要插入的结点个数
if(k==0)
return head;
count=1;
ListNode *p,*q,*pre;//若不是Head开始逆序,pre指向逆序的第一个结点的前一个结点;否则,pre指向逆序的第一个结点
p=head;
pre=p;
while(count<m&&p)
{
count++;
if(p!=head)
pre=pre->next;
p=p->next;
}
q=p->next;//指向待插入结点
count=0;
while(count<k)
{
p->next=q->next;
if(m>1){//说明不是从head开始插入的
q->next=pre->next;
pre->next=q;
}
if(m==1)//说明是从Head插入
{
q->next=pre;
head=q;
pre=q;
}
q=p->next;
count++;
}
return head;
}
};