92翻转部分链表

 

利用头插法解决,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;
    }
};

https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/yi-bu-yi-bu-jiao-ni-ru-he-yong-di-gui-si-lowt/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值