当前位置:网站首页>鏈錶內指定區間反轉
鏈錶內指定區間反轉
2022-07-03 01:01: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-1964: find the longest effective obstacle race route to each position
- [AUTOSAR five methodology]
- Extension of flutter
- Vulkan performance and refinement
- leetcode-1964:找出到每个位置为止最长的有效障碍赛跑路线
- 1.12 - Instructions
- 链表中的节点每k个一组翻转
- [introduction to AUTOSAR seven tool chain]
- 【AutoSAR 七 工具链简介】
- 465. 最优账单平衡 DFS 回溯
猜你喜欢
[AUTOSAR 11 communication related mechanism]
Vulkan performance and refinement
Vulkan-性能及精细化
【爱死机】《吉巴罗》被忽略的细节
全志A40i/T3如何通过SPI转CAN
[shutter] image component (cached_network_image network image caching plug-in)
1.11 - bus
Win10 多种方式解决无法安装.Net3.5的问题
antv x6节点拖拽到画布上后的回调事件(踩大坑记录)
[applet project development -- JD mall] user defined search component of uni app (middle) -- search suggestions
随机推荐
利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
[AUTOSAR 11 communication related mechanism]
Tensorflow 2.x(keras)源码详解之第十五章:迁移学习与微调
Set up nacos2 X cluster steps and problems encountered
测试右移:线上质量监控 ELK 实战
数据分析思维分析犯法和业务知识——分析方法(一)
[daily training] 871 Minimum refueling times
The difference between tail -f, tail -f and tail
[AUTOSAR + IO Architecture]
lex && yacc && bison && flex 配置的問題
Illustrated network: what is virtual router redundancy protocol VRRP?
Vulkan-实践第一弹
正确甄别API、REST API、RESTful API和Web Service之间的异同
飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
Leetcode-224: basic calculator
1.12 - 指令
mysql 多表联合删除
Leetcode-2280: represents the minimum number of line segments of a line graph
【爱死机】《吉巴罗》被忽略的细节
【案例分享】让新时代教育发展与“数”俱进