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;


    }
};
相关推荐
Savior`L5 小时前
二分算法及常见用法
数据结构·c++·算法
mmz12076 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻7 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习7 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~8 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
AndrewHZ8 小时前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法
CoderYanger8 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习9 小时前
面试150——第二周
数据结构·算法·leetcode
freedom_1024_9 小时前
红黑树底层原理拆解
开发语言·数据结构·b树