当前位置:网站首页>鏈錶內指定區間反轉
鏈錶內指定區間反轉
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;
}
};
边栏推荐
- 【JetCache】JetCache的配置说明和注解属性说明
- leetcode-241:为运算表达式设计优先级
- [Luogu p4320] road meets (round square tree)
- 1.12 - Instructions
- Lex & yacc & bison & flex configuration problems
- 线程的启动与优先级
- Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
- Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
- 删除有序链表中重复的元素-II
- 拥抱平台化交付的安全理念
猜你喜欢

Thank you for being together for these extraordinary two years!

Vulkan performance and refinement

Vulkan practice first bullet

Key detection and sinusoidal signal output developed by Arduino

Win10 多种方式解决无法安装.Net3.5的问题
![[overview of AUTOSAR four BSW]](/img/19/c2273bbedb7f8d859e5a3805ed5740.png)
[overview of AUTOSAR four BSW]

世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力

Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud

Nacos+openfeign error reporting solution

Is there a free text to speech tool to help recommend?
随机推荐
拥抱平台化交付的安全理念
【AutoSAR 十 IO架构】
【日常训练】871. 最低加油次数
[AUTOSAR II appl overview]
FPGA - 7系列 FPGA内部结构之Clocking -04- 多区域时钟
数学建模之线性规划(含MATLAB代码)
正确甄别API、REST API、RESTful API和Web Service之间的异同
Win10 can't be installed in many ways Problems with NET3.5
[daily training] 871 Minimum refueling times
Arduino开发之按键检测与正弦信号输出
RK3568开发板评测篇(二):开发环境搭建
1.11 - bus
[AUTOSAR I overview]
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
【AutoSAR 十二 模式管理】
世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
【AutoSAR 四 BSW概述】
The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
[applet project development -- JD mall] user defined search component of uni app (middle) -- search suggestions