当前位置:网站首页>链表内指定区间反转
链表内指定区间反转
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;
}
};
边栏推荐
- kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
- 全志A40i/T3如何通过SPI转CAN
- 【AutoSAR 十三 NVM】
- Extension of flutter
- Foundations of data science is free to download
- Test shift right: Elk practice of online quality monitoring
- Leetcode-2115: find all the dishes that can be made from the given raw materials
- Rust ownership (very important)
- [AUTOSAR VI description document]
- Leetcode-871: minimum refueling times
猜你喜欢

【AutoSAR 七 工具链简介】

File operation io-part2
![[AUTOSAR VI description document]](/img/3d/1382acbc4054ab218485a12b7b4e6b.png)
[AUTOSAR VI description document]

Linux Software: how to install redis service

antv x6节点拖拽到画布上后的回调事件(踩大坑记录)

University of Oslo: Li Meng | deep reinforcement learning based on swing transformer

瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南

研发一款国产ARM智能边缘计算网关需要什么

Shell implements basic file operations (SED edit, awk match)

FPGA - 7系列 FPGA内部结构之Clocking -04- 多区域时钟
随机推荐
Array and collection performance comparison
[flutter] icons component (load the built-in icon of flutter | display the material design icon completely)
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
Extension of flutter
Vulkan-性能及精细化
【C语言】分支和循环语句(上)
Is there a free text to speech tool to help recommend?
Lex & yacc & bison & flex configuration problems
How to find out the currently running version of Solr- How do I find out version of currently running Solr?
[AUTOSAR + IO Architecture]
Sentry developer contribution Guide - configure pycharm
cordova-plugin-device获取设备信息插件导致华为审核不通过
Advanced pointer (I)
【AutoSAR 十二 模式管理】
Deep analysis of data storage in memory
tail -f 、tail -F、tailf的区别
2022中国3D视觉企业(引导定位、分拣场景)厂商名单
Vulkan-实践第一弹
【案例分享】让新时代教育发展与“数”俱进
[AUTOSAR 11 communication related mechanism]