当前位置:网站首页>链表内指定区间反转
链表内指定区间反转
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;
}
};
边栏推荐
- leetcode-224:基本计算器
- [AUTOSAR II appl overview]
- 瑞萨电子RZ/G2L开发板上手评测
- The difference between relational database and non relational database
- [flutter] icons component (load the built-in icon of flutter | display the material design icon completely)
- Leetcode-224: basic calculator
- 【AutoSAR 二 AppL概述】
- [introduction to AUTOSAR seven tool chain]
- [AUTOSAR five methodology]
- Win10 can't be installed in many ways Problems with NET3.5
猜你喜欢
In the first half of 2022, there are 10 worth seeing, and each sentence can bring you strength!
Thank you for being together for these extraordinary two years!
Rust所有权(非常重要)
【AutoSAR 三 RTE概述】
Initial order of pointer (basic)
【AutoSAR 六 描述文件】
First hand evaluation of Reza electronics rz/g2l development board
Rk3568 development board evaluation (II): development environment construction
Win10 can't be installed in many ways Problems with NET3.5
瑞萨电子RZ/G2L开发板上手评测
随机推荐
Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
Leetcode-849: maximum distance to the nearest person
Win10 多种方式解决无法安装.Net3.5的问题
【AutoSAR 一 概述】
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
Array common operation methods sorting (including ES6) and detailed use
详解RDD基本概念、RDD五大属性
[shutter] image component (load network pictures | load static pictures | load local pictures | path | provider plug-in)
The difference between tail -f, tail -f and tail
[jetcache] jetcache configuration description and annotation attribute description
机器学习:numpy版本线性回归预测波士顿房价
Shell implements basic file operations (SED edit, awk match)
Overlay of shutter (Pop-Up)
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
【C语言】分支和循环语句(上)
Thank you for being together for these extraordinary two years!
【AutoSAR 十 IO架构】
【JetCache】JetCache的配置说明和注解属性说明
腾讯云免费SSL证书扩展文件含义
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议