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;
}
相关推荐
Warren2Lynch14 分钟前
掌握 UML 构造型、标记定义与标记值:面向领域特定建模的 UML 扩展全面指南
大数据·算法·uml
1570925113443 分钟前
【无标题】
开发语言·python·算法
稚南城才子,乌衣巷风流1 小时前
换根法(Rerooting)算法详解
算法
晓子文集1 小时前
Tushare接口文档:期货交易日历(fut_trade_cal)
大数据·算法
^yi2 小时前
【Linux系统编程】进程状态的理解
算法·僵尸进程·孤儿进程·进程状态·挂起状态·阻塞状态
冻柠檬飞冰走茶3 小时前
PTA基础编程题目集 7-7 12-24小时制(C语言实现)
c语言·开发语言·数据结构·算法
长不胖的路人甲3 小时前
二叉排序树(BST)Java 完整实现 + 删除思路详解
java·开发语言·算法
geovindu3 小时前
python: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·python·算法·搜索算法
长不胖的路人甲3 小时前
可达性分析法(根搜索算法)完整详解
java·jvm·算法
runafterhit3 小时前
python基础语法命令(C程序员刷leetcode)
c语言·python·leetcode