当前位置:网站首页>链表内指定区间反转
链表内指定区间反转
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;
}
};
边栏推荐
- Teach you JDBC hand in hand -- structure separation
- Initial order of pointer (basic)
- Shell implements basic file operations (cutting, sorting, and de duplication)
- 【JetCache】JetCache的配置说明和注解属性说明
- leetcode-2115:从给定原材料中找到所有可以做出的菜
- leetcode-1964:找出到每个位置为止最长的有效障碍赛跑路线
- Array common operation methods sorting (including ES6) and detailed use
- Rust所有权(非常重要)
- Machine learning: numpy version linear regression predicts Boston house prices
- 数学建模之线性规划(含MATLAB代码)
猜你喜欢
12_微信小程序之微信视频号滚动自动播放视频效果实现
世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
How SQLSEVER removes data with duplicate IDS
【AutoSAR 一 概述】
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
Detailed explanation of pod life cycle
【AutoSAR 八 OS】
【AutoSAR 四 BSW概述】
Unity learns from spaceshooter to record the difference between fixedupdate and update in unity for the second time
随机推荐
Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
KingbaseES ALTER TABLE 中 USING 子句的用法
Is there a free text to speech tool to help recommend?
Rust ownership (very important)
Thank you for being together for these extraordinary two years!
【爱死机】《吉巴罗》被忽略的细节
Teach you JDBC hand in hand -- structure separation
指针进阶(一)
Test shift right: Elk practice of online quality monitoring
cordova-plugin-device获取设备信息插件导致华为审核不通过
AEM: Nanlin fan Ben et al. - plant rhizosphere growth promoting bacteria control soybean blight
Array common operation methods sorting (including ES6) and detailed use
How to systematically learn machine learning
测试右移:线上质量监控 ELK 实战
Vulkan并非“灵药“
Infrared thermography temperature detection system based on arm rk3568
Initial order of pointer (basic)
1.11 - 总线
Detailed explanation of pod life cycle
Attributeerror: 'tuple' object has no attribute 'layer' problem solving