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;


    }
};
相关推荐
木尼1238 分钟前
leedcode 算法刷题第三十一天
算法·leetcode·职场和发展
长安——归故李30 分钟前
【modbus学习】
java·c语言·c++·学习·算法·c#
Boop_wu44 分钟前
[数据结构] LinkedList
数据结构
兴科Sinco1 小时前
[leetcode 1]给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数[力扣]
python·算法·leetcode
沐怡旸1 小时前
【算法--链表】138.随机链表的复制--通俗讲解
算法·面试
anlogic1 小时前
Java基础 9.10
java·开发语言·算法
薛定谔的算法1 小时前
JavaScript单链表实现详解:从基础到实践
数据结构·算法·leetcode
CoovallyAIHub1 小时前
CostFilter-AD:用“匹配代价过滤”刷新工业质检异常检测新高度! (附论文和源码)
深度学习·算法·计算机视觉
幻奏岚音1 小时前
《数据库系统概论》第一章 初识数据库
数据库·算法·oracle
你好,我叫C小白1 小时前
贪心算法(最优装载问题)
算法·贪心算法·最优装载问题