当前位置:网站首页>【刷题笔记】链表内指定区间反转
【刷题笔记】链表内指定区间反转
2022-07-28 23:41:00 【柒海啦】
题目:
描述
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。
例如:
给出的链表为 1\to 2 \to 3 \to 4 \to 5 \to NULL1→2→3→4→5→NULL, m=2,n=4m=2,n=4,
返回 1\to 4\to 3\to 2\to 5\to NULL1→4→3→2→5→NULL.
数据范围: 链表长度 0 < size \le 10000<size≤1000,0 < m \le n \le size0<m≤n≤size,链表中每个节点的值满足 |val| \le 1000∣val∣≤1000
要求:时间复杂度 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}
解答:
此题只要掌握了反转链表一般就能解的出来,至于给的这个区间只需要遍历到此处即可。
我们的目的是在遍历的同时将整个链表反转了。那么我们是不是可以将一开始的节点固定住,然后每次循环的时候,只需将此固定节点后一个移动到固定节点前面,让固定节点前面一个固定节点指向此移动节点,然后移动节点指向一开始前固定节点的下一个。(一开始指向第一个节点,然后就是指向第二个,这样取的时候就相当于在前固定节点和固定节点中重新排了个倒序)。这样就可一移动相差多少步即可。
前固定节点为res,固定节点是cur。为了防止是一开始从第一个就开始排,那么这个前固定节点就需要创建一个头节点,值随意,然后指向头,这样返回的时候返回其指向的头即可。
然后通过循环即i < m找到最开始的那个节点,res就等于此节点前一个,那么cur就是指向后一个。
代码:
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
// write code here
struct ListNode* res = (struct ListNode*)malloc(sizeof(struct ListNode));
res->next = head;
struct ListNode* pre = res;
struct ListNode* cur = head;
for (int i = 1; i < m; i++)
{
pre = cur;
cur = cur->next;
}
for(int i = m; i < n; i++)
{
struct ListNode* temp = cur->next;
cur->next = temp->next;
temp->next = pre->next;
pre->next = temp;
}
return res->next;
}边栏推荐
猜你喜欢
随机推荐
[Yugong series] go teaching course in July 2022, an array of 020 go containers
Andriod6.0 low power mode (turn off WiFi, Bluetooth, GPS, screen brightness, etc.)
Depth first search (DFS) and its matlab code
Rk3399 9.0 driver add powser button
新拟态个人引导页源码
Xinchi technology released the latest flagship product of G9 series, equipped with six A55 cores with 1.8GHz dominant frequency
时间序列数据的预处理方法总结
SQL Server 只有数据库文件,没有日志文件,恢复数据时报1813错误的解决方案
Requestvideoframecallback() simple instance
Selenium wire obtains Baidu Index
异步模式之工作线程
Jupyter notebook中5个有趣的魔法命令
数学建模及其基础知识详解(化学常考知识点)
状态压缩dp-蒙德里安的梦想
armeabi-v7a架构(sv7a)
Anomaly detection and unsupervised learning (1)
Educational Codeforces Round 132 (Rated for Div. 2)【A~C】
CUDA相关
DRF -- authentication, authority, frequency source code analysis, global exception handling, automatic generation of interface documents, RBAC introduction
Error reporting: Rong Lianyun sends SMS verification code message 500




![[untitled]](/img/28/db3b2e1985dc9acf41cdf2004ea0d5.png)



