Leetcode 92 反转链表II

反转链表II

    • [题解1 一遍遍历(穿针引线)](#题解1 一遍遍历(穿针引线))

给你单链表的头指针 head 和两个整数 leftright ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表

提示:

  1. 链表中节点数目为 n
  2. 1 <= n <= 500
  3. -500 <= Node.val <= 500
  4. 1 <= left <= right <= n

进阶: 你可以使用一趟扫描完成反转吗?

题解1 一遍遍历(穿针引线)

cpp 复制代码
/**
 * 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) {
        if(left == right) return head;
        ListNode* dummynode = new ListNode(-1);
        dummynode->next = head;
        ListNode* pre = dummynode;
        for(int i = 0; i < left-1; i++)
            pre = pre->next; // 不要动
        ListNode* cur = pre->next; // 反转的第一个结点
        ListNode* nex;
        for(int i = 0; i < right-left; i ++){
            // 穿针引线:
            // cur是left对应的结点,没变过
            // 实际上每次操作都只和cur->next(nex)\pre->next\nex->next有关(3个链)
            nex = cur->next;
            cur->next = nex->next;
            nex->next = pre->next;

            pre->next = nex;
        }
        return dummynode->next;


    }
};
相关推荐
Themberfue11 分钟前
基础算法之双指针--Java实现(下)--LeetCode题解:有效三角形的个数-查找总价格为目标值的两个商品-三数之和-四数之和
java·开发语言·学习·算法·leetcode·双指针
陈序缘36 分钟前
LeetCode讲解篇之322. 零钱兑换
算法·leetcode·职场和发展
-$_$-39 分钟前
【LeetCode HOT 100】详细题解之二叉树篇
数据结构·算法·leetcode
大白飞飞40 分钟前
力扣203.移除链表元素
算法·leetcode·链表
尘心cx1 小时前
数据结构-栈
数据结构
学无止境\n1 小时前
[C语言]指针和数组
c语言·数据结构·算法
黄俊懿1 小时前
【深入理解SpringCloud微服务】手写实现各种限流算法——固定时间窗、滑动时间窗、令牌桶算法、漏桶算法
java·后端·算法·spring cloud·微服务·架构
新缸中之脑1 小时前
Llama 3.2 安卓手机安装教程
前端·人工智能·算法
夜雨翦春韭1 小时前
【代码随想录Day29】贪心算法Part03
java·数据结构·算法·leetcode·贪心算法
Curry_Math2 小时前
Acwing 区间DP & 计数类DP
算法