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;
}
相关推荐
Nil20836 分钟前
leetcode 48旋转图像
算法·leetcode·职场和发展
嘟嘟07171 小时前
顺时针螺旋填充 n×n 矩阵:手撕 generateMatrix 的四个 for 循环
javascript·算法·面试
Nil2081 小时前
leetcode 206反转链表
算法·leetcode·链表
Kstheme1 小时前
大模型内部是怎么运作的?从「一个神经元」拆到「残差流」
算法
郝学胜_神的一滴1 小时前
并查集深度入门:从玄学抽象到 QuickFind & QuickUnion 源码实战
数据结构·算法
GeekZHR1 小时前
C语言指针2:数组名、二级指针、指针数组,一次把“指针和数组“讲透
c语言·数据结构·算法·指针
h_a_o777oah1 小时前
【算法基础】卡特兰数:递推定义与折线对称公式推导及解题策略
c++·算法·acm·组合数学·卡特兰数·反射原理·动态规划dp
JAI科研2 小时前
Deepseek Agent Harness教程(二) | DeepSeek Harness 设计思路
人工智能·深度学习·算法·机器学习·自然语言处理·transformer·vllm
还不秃顶的计科生2 小时前
具身智能论文学习10:π0: A Vision-Language-Action Flow Model for General Robot Control
人工智能·深度学习·算法·机器学习·语言模型·vla·vlm
happyprince2 小时前
02-具体观 — Cordis 算法与实现剖析
算法