力扣-92题 反转链表II(C++)- 增设dummyHead

本文详细解析了LeetCode问题92的`reverseBetween`,介绍了使用迭代和递归两种方法来实现链表的反转,并探讨了两种方法在时间和空间复杂度上的区别。通过实例演示了如何在链表中指定区间进行反转,适合初学者和进阶者学习链表操作技巧。
摘要由CSDN通过智能技术生成

题目链接:https://leetcode-cn.com/problems/reverse-linked-list-ii/
题目如下:
在这里插入图片描述
在这里插入图片描述
思路:
在这里插入图片描述

/**
 * 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* dummyHead=new ListNode(-1);
        dummyHead->next=head;
        auto pre=dummyHead,cur=dummyHead->next;

        for(int i=0;i<left-1;i++){
            pre=cur;
            cur=cur->next;
        }

        auto a=pre,b=cur;//保存住,作为之后使用

        for(int i=left;i<=right;i++){
            auto temp=cur->next;
            cur->next=pre;
            pre=cur;cur=temp;
        }

        b->next=cur;
        a->next=pre;

        ListNode* result=dummyHead->next;
        delete dummyHead;

        return result;

        /*
        ListNode* cur=head;
        ListNode* pre=NULL;

        for(int i=0;i<left-1;i++){
            pre=cur;
            cur=cur->next;
        }
        auto a=pre,b=pre->next;//当left为1时头节点会发生变化,故此,需增加一个dummy节点

        for(int i=left;i<=right;i++){
            ListNode* temp=cur->next;
            cur->next=pre;
            pre=cur;cur=temp;
        }

        b->next=cur;
        a->next=pre;
        
        return head;
        */
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值