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;


    }
};
相关推荐
浅川.2515 分钟前
STL专项:stack 栈
数据结构·stl·stack
YGGP1 小时前
【Golang】LeetCode 32. 最长有效括号
算法·leetcode
自然常数e1 小时前
字符函数和字符串函数
c语言·算法·visual studio
youngee112 小时前
hot100-56最小栈
数据结构
leaves falling2 小时前
c语言分数求和
算法
Das12 小时前
【机器学习】01_模型选择与评估
人工智能·算法·机器学习
星轨初途2 小时前
郑州轻工业大学2025天梯赛解题
c++·经验分享·笔记·算法·链表·剪枝
不忘不弃2 小时前
从字符串中提取数字
数据结构·算法
点云SLAM3 小时前
C++ 引用折叠(Reference Collapsing)和示例讲解说明
数据结构·c++·标准算法·完美转发·代码性能优化·c++ 引用折叠·typedef / using