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;
}
相关推荐
旖-旎12 小时前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
@小码农12 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
Wect13 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·算法·typescript
糖果店的幽灵13 小时前
决策树详解与sklearn实战
算法·决策树·sklearn
Lewiis13 小时前
趣谈排序算法
算法·排序算法
ComputerInBook13 小时前
数字图像处理(4版)——第 8 章——图像压缩与水印(上)(Rafael C.Gonzalez&Richard E. Woods)
人工智能·算法·计算机视觉·图像压缩·图像水印
刀法如飞14 小时前
Python列表去重:从新手三连到高阶特技,20种解法全收录
python·算法·编程语言
minji...14 小时前
算法题 动态规划
算法·动态规划
水蓝烟雨14 小时前
3337. 字符串转换后的长度 II
算法·leetcode
MegaDataFlowers14 小时前
SiliconCompiler workflow
算法