当前位置:网站首页>鏈錶內指定區間反轉
鏈錶內指定區間反轉
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;
}
};
边栏推荐
- 深度剖析数据在内存中的存储
- Extension of flutter
- University of Oslo: Li Meng | deep reinforcement learning based on swing transformer
- Solve the cache problem of reactnative using WebView
- Win10 can't be installed in many ways Problems with NET3.5
- First hand evaluation of Reza electronics rz/g2l development board
- Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud
- [Luogu p4320] road meets (round square tree)
- 【AutoSAR 一 概述】
- Thread start and priority
猜你喜欢

Arduino开发之按键检测与正弦信号输出

安全运营四要素之资产、脆弱性、威胁和事件

指针进阶(一)

RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide

百度智能云牵头打造智能云综合标准化平台

Test shift right: Elk practice of online quality monitoring

tail -f 、tail -F、tailf的区别

指针初阶(基础)

【爱死机】《吉巴罗》被忽略的细节

Nacos+openfeign error reporting solution
随机推荐
In the first half of 2022, there are 10 worth seeing, and each sentence can bring you strength!
Basic use of sringcloud & use of component Nacos
Is there a free text to speech tool to help recommend?
飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
2022.2.14 resumption
Tensorflow 2.x(keras)源码详解之第十五章:迁移学习与微调
RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide
[case sharing] let the development of education in the new era advance with "number"
KingbaseES ALTER TABLE 中 USING 子句的用法
[overview of AUTOSAR four BSW]
Advanced pointer (I)
About qbytearray storage hexadecimal and hexadecimal conversion
mysql 多表联合删除
Vulkan performance and refinement
What is needed to develop a domestic arm intelligent edge computing gateway
Rust string slicing, structs, and enumeration classes
[jetcache] jetcache configuration description and annotation attribute description
[AUTOSAR five methodology]
leetcode-849:到最近的人的最大距离
腾讯云免费SSL证书扩展文件含义