当前位置:网站首页>链表内指定区间反转
链表内指定区间反转
2022-07-03 00:29:00 【Schuyler Hu】
问题
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n),空间复杂度 O(1)。
思路
- 采用双指针移动到指定位置: pre 移动到挪动区间的起始位置的前一个位置,cur 移动到挪动区间的起始位置。
- 连接 cur 与 cur 的下下个元素,断开 cur 与 next 的连接;next 连接到 pre 后一元素之前;pre 指向 next。
代码实现
/** * struct ListNode { * int val; * struct ListNode *next; * }; */
class Solution {
public:
/** * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */
ListNode* reverseBetween(ListNode* head, int m, int n) {
// write code here
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* pre = dummyHead;
// 0 < m < size,所以本题链表下标从 1 开始,pre 指向翻转区间的起始前一个位置
for (int i = 1; i < m; i++)
{
pre = pre->next;
}
ListNode* cur = pre->next;
for (int i = m; i < n; i++)
{
ListNode* next = cur->next;
// 断开 cur 与 next 的连接
cur->next = next->next;
// 将后续的 next 移动到 pre 下一个元素前
next->next = pre->next;
// 连接 pre 和 next
pre->next = next;
}
return dummyHead->next;
}
};
边栏推荐
- 瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南
- Win10 多种方式解决无法安装.Net3.5的问题
- 线程的启动与优先级
- [love crash] neglected details of gibaro
- 465. 最优账单平衡 DFS 回溯
- Win10 can't be installed in many ways Problems with NET3.5
- Extension of flutter
- [case sharing] let the development of education in the new era advance with "number"
- Thank you for being together for these extraordinary two years!
- Teach you JDBC hand in hand -- structure separation
猜你喜欢
Linux Software: how to install redis service
【AutoSAR 五 方法论】
【AutoSAR 十一 通信相关机制】
【AutoSAR 二 AppL概述】
antv x6节点拖拽到画布上后的回调事件(踩大坑记录)
Reading and writing speed of Reza rz/g2l arm development board storage and network measurement
[AUTOSAR 11 communication related mechanism]
世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
[AUTOSAR nine c/s principle Architecture]
How SQLSEVER removes data with duplicate IDS
随机推荐
利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
详解RDD基本概念、RDD五大属性
Leetcode-241: designing priorities for operational expressions
Deep analysis of data storage in memory
[daily training] 871 Minimum refueling times
【JetCache】JetCache的配置说明和注解属性说明
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
The difference between relational database and non relational database
这不平凡的两年,感谢我们一直在一起!
Infrared thermography temperature detection system based on arm rk3568
腾讯云免费SSL证书扩展文件含义
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
[AUTOSAR II appl overview]
[AUTOSAR 11 communication related mechanism]
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
[overview of AUTOSAR four BSW]
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
数学建模之线性规划(含MATLAB代码)
[AUTOSAR XIII NVM]
leetcode-1964:找出到每个位置为止最长的有效障碍赛跑路线