Leetcode训练计划(七) --92.反转链表二

92.反转链表二

给你单链表头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

示例 1:
在这里插入图片描述

输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]

示例 2:

输入:head = [5], left = 1, right = 1
输出:[5]

提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n

题解思路

思路总体是比较好理解的,就是边界处理、代码实现比较考究编码功底,题主太菜了,折磨半个下午呜呜呜。

1、创建虚拟头节点指定head
2、遍历链表定位 left和right
3、切割链表
4、反转链表,可借鉴题206
5、拼接链表

c++代码实现

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        if(!head || !head->next ||right==left){
            return head;
        }
        //创建虚拟子节点。锁定头节点,因为有可能头结点会被反转
        ListNode *dummyNode = new ListNode(-1);
        dummyNode->next=head;
        ListNode *newhead=dummyNode;
        ListNode *pre = nullptr, *cur;
        ListNode *newpre = nullptr,*newcur;

        //定位两个坐标位置,
        for(int i=1;i<left;i++){
            newhead=newhead->next;
        }
        newcur=newhead;
        for(int i=1;i<=right-left+1;i++){
            newhead=newhead->next;
        }
        pre=newhead;
        //确定边界点位置 newcur,cur,pre,newpre四个点。
        cur=newcur->next;
        newpre = pre->next;
        //切断链表
        newcur->next=nullptr;
        pre->next=nullptr;
        //反转链表  原题206.反转链表
        ListNode *cur1=cur, *pre1=nullptr;
        while(cur1){
            auto temp=cur1->next;
            cur1->next=pre1;
            pre1=cur1;
            cur1=temp;
        }
        //拼接链表
        newcur->next=pre;
        cur->next=newpre;
        return dummyNode->next;
    }
};

提交记录
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值