leetcode:92. 反转链表 II

题目要求

要对指定区域内的节点进行反转,首先,可以先定义一个哑节点,让其作为头节点指向第一个节点,以便后面解决left在第一个节点的情况:

cpp 复制代码
struct ListNode *pre_head = (struct ListNode *)malloc(sizeof(struct ListNode));
    pre_head->next = head;

先讨论left==right这种特殊情况:

cpp 复制代码
if(left == right){
        return head;
    }

然后定义一个pre节点和cur节点,pre节点始终指向left的前一个节点,cur始终指向left节点:

cpp 复制代码
struct ListNode *pre = cur;
    cur = cur->next;

后面需要依次将left后面的节点放到pre的后面,总共需要循环(right-left)次,所有用for函数,在函数内先定义一个next节点指向cur的下一个节点,然后先把cur的下一个节点指向再下一个,再将cur的next放到pre的后面,最后将pre指向cur的next:

cpp 复制代码
for(int i = 0; i < (right - left); i++){
        struct ListNode *next = cur->next;
        cur->next = next->next;
        next->next = pre->next;
        pre->next = next;
    }

完整代码:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseBetween(struct ListNode* head, int left, int right) {
    struct ListNode *pre_head = (struct ListNode *)malloc(sizeof(struct ListNode));
    pre_head->next = head;
    struct ListNode *cur = pre_head;
    if(left == right){
        return head;
    }
    for(int i = 1; i < left; i++){
        cur = cur->next;
    }
    struct ListNode *pre = cur;
    cur = cur->next;
    for(int i = 0; i < (right - left); i++){
        struct ListNode *next = cur->next;
        cur->next = next->next;
        next->next = pre->next;
        pre->next = next;
    }
    return pre_head->next;
}
相关推荐
TMT星球9 分钟前
魔法原子上交会首秀VLA K02大模型,完成具身智能从“执行”到“理解”的能力跃迁
人工智能·算法·机器学习
2301_7644413311 分钟前
番茄钟+AI:高效专注的秘密武器
人工智能·算法·数学建模·动态规划·交互
影寂ldy14 分钟前
C# 泛型委托
java·算法·c#
星马梦缘28 分钟前
算法设计与分析 作业三 纯答案
算法
zzz_236835 分钟前
【Java基础】链表的七十二变——从LRU缓存到手写浏览器前进后退
java·链表·缓存
不知名的老吴1 小时前
经典算法题之行星碰撞
数据结构·算法
西安邮电大学1 小时前
有关数组的经典算法题
java·后端·其他·算法·面试
学Linux的语莫1 小时前
大模型微调数据集格式详解:Alpaca、ShareGPT、DPO、KTO、预训练数据怎么构建?
人工智能·算法·机器学习·微调格式
wayz111 小时前
Momentum:UO(终极震荡指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程
Boom_Shu1 小时前
浅拷贝与深拷贝
开发语言·c++·算法