当前位置:网站首页>鏈錶內指定區間反轉
鏈錶內指定區間反轉
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;
}
};
边栏推荐
- 【AutoSAR 八 OS】
- 比较版本号
- lex && yacc && bison && flex 配置的問題
- 利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
- 【AutoSAR 七 工具链简介】
- 1.12 - Instructions
- The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
- 【AutoSAR 三 RTE概述】
- matlab将数字矩阵保存为地理空间数据出错,显示下标索引必须为正整数类型或逻辑类型,解决
- leetcode-241:为运算表达式设计优先级
猜你喜欢
随机推荐
Leetcode-224: basic calculator
链表内指定区间反转
Test shift right: Elk practice of online quality monitoring
【AutoSAR 一 概述】
leetcode-2115:从给定原材料中找到所有可以做出的菜
Leetcode 294. Flip game II (game theory)
[AUTOSAR eight OS]
Vulkan practice first bullet
[daily training] 871 Minimum refueling times
Foundations of data science is free to download
链表中的节点每k个一组翻转
【爱死机】《吉巴罗》被忽略的细节
【AutoSAR 五 方法论】
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
[AUTOSAR XIII NVM]
[AUTOSAR I overview]
12_微信小程序之微信视频号滚动自动播放视频效果实现
[AUTOSAR II appl overview]
File operation io-part2
Leetcode-871: minimum refueling times
![[AUTOSAR eight OS]](/img/ac/fbc84c077ff9c94c840e1871171d19.png)






![[AUTOSAR twelve mode management]](/img/42/292e3da3f5d488a1e8c10ea9bbfbab.png)

