方法一
与第206题方法类似,只不过要把反转后的部分连接起来,我用l和r两个变量记录,设置虚拟头节点p省去left在开头时的情况讨论
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode *p=new ListNode(0,head);
ListNode *pre=p,*cur,*l,*r,*next;
for(int i=0;i<left-1;i++)
pre=pre->next;
cur=pre->next;
l=pre;
r=cur;
for(int i=0;i<right-left+1;i++){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
l->next=pre;
r->next=next;
return p->next;
}
};
方法二 头插法
pre和cur一直不变,每次将cur后面的节点插在pre后面
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode *p=new ListNode(0,head);
ListNode *pre=p,*cur;
for(int i=0;i<left-1;i++)
pre=pre->next;
cur=pre->next;
for(int i=0;i<right-left;i++){
ListNode *next=cur->next;
cur->next=next->next;
next->next=pre->next;
pre->next=next;
}
return p->next;
}
};