当前位置:网站首页>链表内指定区间反转
链表内指定区间反转
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;
}
};
边栏推荐
- [overview of AUTOSAR four BSW]
- RK3568开发板评测篇(二):开发环境搭建
- Nacos+openfeign error reporting solution
- Leetcode-2115: find all the dishes that can be made from the given raw materials
- RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide
- kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
- tail -f 、tail -F、tailf的区别
- University of Oslo: Li Meng | deep reinforcement learning based on swing transformer
- 【AutoSAR 九 C/S原理架构】
- 【AutoSAR 六 描述文件】
猜你喜欢

leetcode-2280:表示一个折线图的最少线段数

瑞萨RZ/G2L ARM开发板存储读写速度与网络实测

Infrared thermography temperature detection system based on arm rk3568

University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement

(C语言)数据的存储

利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度

Illustrated network: what is virtual router redundancy protocol VRRP?
![[AUTOSAR eight OS]](/img/ac/fbc84c077ff9c94c840e1871171d19.png)
[AUTOSAR eight OS]

Win10 多种方式解决无法安装.Net3.5的问题

How to convert Quanzhi a40i/t3 to can through SPI
随机推荐
Leetcode-1964: find the longest effective obstacle race route to each position
Key detection and sinusoidal signal output developed by Arduino
Lex & yacc & bison & flex configuration problems
[shutter] image component (cached_network_image network image caching plug-in)
Understanding and distinguishing of some noun concepts in adjustment / filtering
如何系统学习机器学习
线程的启动与优先级
【AutoSAR 八 OS】
数组与集合性能比较
数学建模之线性规划(含MATLAB代码)
An excellent orm in dotnet circle -- FreeSQL
AEM: Nanlin fan Ben et al. - plant rhizosphere growth promoting bacteria control soybean blight
leetcode-2280:表示一个折线图的最少线段数
Leetcode-224: basic calculator
Leetcode-2280: represents the minimum number of line segments of a line graph
2022上半年值得被看见的10条文案,每一句都能带给你力量!
瑞萨电子RZ/G2L开发板上手评测
【AutoSAR 十三 NVM】
Array common operation methods sorting (including ES6) and detailed use
lex && yacc && bison && flex 配置的问题