利用头插法解决,206也是反转链表,也可以用头插法
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode*dummy=new ListNode(-1,head);
ListNode*pre=dummy;
for(int i=1;i<left;i++){
pre=pre->next;
head=head->next;
}
for(int j=0;j<right-left;j++){
ListNode*temp=head->next;
head->next=temp->next;
temp->next=pre->next;
pre->next=temp;
}
return dummy->next;
}
};
递归
先考虑一下递归前n个节点
由于链表是从1开始的,所以只需要递归或者迭代n-1次就能从第一个节点,到最后反转位置,所以base case就是n=1的时候,同时在这个n=1的递归中,head是3那个位置的节点,并且相对于反转整个链表,需要记录一下后驱节点,因为最后一个不是nullptr
ListNode*successor;
ListNode*myreverse(Listnode*head,int n){
if(n==1){
successor=head->next;
return head;
}
ListNode*last=myreverse(head->next,n-1);
head->next->next=head;
head->next=successor;
return last;
}
如果反转n,m个节点, 则相当于一直递归直到找到第一个需要翻转的位置,这不就是翻转前n个节点了么
class Solution {
public:
ListNode*successor=nullptr;
ListNode*myreverse(ListNode*head,int num){
if(num==1){
successor=head->next;
return head;
}
ListNode*last=myreverse(head->next,num-1);
head->next->next=head;
head->next=successor;
return last;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(left==1)
return myreverse(head,right);
head->next=reverseBetween(head->next,left-1,right-1);
return head;
}
};