当前位置:网站首页>链表内指定区间反转
链表内指定区间反转
2022-07-27 02:50:00 【利刃Cc】
描述
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。
例如:
给出的链表为 1→ 2→ 3 → 4→ 5 → NULL, m=2,n=4m=2,n=4,
返回 1→ 4→ 3 → 2 → 5 → NULL。
要求:时间复杂度 O(n)O(n) ,空间复杂度 O(n)O(n)
进阶:时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)
示例1
输入:{1,2,3,4,5},2,4
返回值:{1,4,3,2,5}
示例2
输入:{5},1,1
返回值:{5}
方法:头插法迭代
在学会了BM1.反转链表之后,要解决这个问题就很简单了,前一题是整个链表反转,这一题是部分反转,这上一题就是这道题的前置问题啊。那我们肯定是要先找到了第m个位置才能开始反转链表,而反转的部分就是从第m个位置到第n个位置,反转这部分的时候就参照BM1.反转链表
具体做法:
- step 1:我们可以在链表前加一个表头,后续返回时去掉就好了,因为如果要从链表头的位置开始反转,在多了一个表头的情况下就能保证第一个节点永远不会反转,不会到后面去。
- step 2:使用两个指针,一个指向当前节点,一个指向前序节点。
- step 3:依次遍历链表,到第m个的位置。
- step 4:对于从m到n这些个位置的节点,依次断掉指向后续的指针,反转指针方向。
- step 5:返回时去掉我们添加的表头。
/** * 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) {
//创建一个新表头
ListNode* newhead = new ListNode(-1);
newhead->next = head;
ListNode* pre = newhead;
ListNode* cur = head;
for(int i = 1; i < m; ++i) //找到m的位置
{
pre = cur;
cur = cur->next;
}
for(int i = m; i < n; ++i) //从m反转到n
{
ListNode* next = cur->next;
cur->next = next->next;
next->next = pre->next;
pre->next = next;
}
return newhead->next;
}
};
边栏推荐
猜你喜欢

Is Jiufang intelligent investment a regular company? Talk about Jiufang intelligent investment

Redis(九) - Redis之分布式锁

开机启动流程及营救模式

NFT数字藏品系统开发:老牌文学杂志玩起新潮数字藏品

科目三: 济南章丘五号线

Detailed analysis of trajectory generation tool in psins toolbox
![[Yugong series] July 2022 go teaching course 018 switch of branch structure](/img/50/171a083713597f1b5643835377a12d.png)
[Yugong series] July 2022 go teaching course 018 switch of branch structure

JVM原理简介

Plato farm has a new way of playing, and the arbitrage eplato has secured super high returns

Subject 3: Jinan Zhangqiu line 6
随机推荐
三种常见的移动底盘运动学模型分析
Kotlin中lateinit和lazy的原理区别是什么
Feitengtengrui d2000 won the "top ten hard core technologies" award of Digital China
知识图谱:知识表示
函数指针与回调函数
注释有点好玩哦
URDF_ Xcaro
B. ICPC Balloons
LeetCode 第二十七天
PSINS工具箱中轨迹生成工具详细解析
There is no problem reading from flick CDC to mysql8 and mysql5. What should I do?
VR全景现在是不是刚需?看完你就明白了
SkyWalking分布式系统应用程序性能监控工具-中
356页14万字高端商业办公综合楼弱电智能化系统2022版
A. Parkway Walk
Program to change the priority of the process in LabVIEW
使用redis c库,异步内存泄露的问题
DataX cannot connect to the corresponding database (yes under windows, but failed under Linux)
暑假加餐|有钱人和你想的不一样(第5天)+电力系统潮流仿真(文档和Matlab代码)
Regression testing: meaning, challenges, best practices and tools