当前位置:网站首页>利用递归和链表头插法实现链表成组的翻转——LeetCode25 K个一组翻转链表
利用递归和链表头插法实现链表成组的翻转——LeetCode25 K个一组翻转链表
2022-07-28 21:51:00 【dor.yang】
题目内容
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
示例 2:
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]
提示:
链表中的节点数目为 n
1 <= k <= n <= 5000
0 <= Node.val <= 1000
进阶:你可以设计一个只用 O(1) 额外内存空间的算法解决此问题吗?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-nodes-in-k-group
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的题解思路
这道题的话和之前的那个两两一组对调有一定的相似之处,不过区别在于这里我们是k个一组进行翻转。
对于链表的翻转,我一开始确实也是不太熟练,不过画图试了一下之后就大概理解了
我们需要三个指针,两个用来记录翻转好的头尾,一个用来标定新一个插头的节点。
我们还需要一个标记,告诉系统什么时候一组的翻转完成了。
完成了一组之后,后面的我们直接重复这个操作就可以了,值得注意的是,head节点因为不断插头的原理,正好指向了下一组节点的头,所以可以直接递归。
最后运行,没有想到效果还挺好的。
实现代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* now=head;
ListNode* l=head;
for(int i=0;i<k;i++){
if(now==nullptr){
return head;
}
now=now->next;
}
// now=now->next;
if(k==1){
return head;
}
ListNode* biao=head->next;
while(biao!=now){
head->next=biao->next;
biao->next=l;
l=biao;
if(head->next==now){
break;
}
biao=head->next;
}
head->next=reverseKGroup(head->next,k);
return biao;
}
};
ps:以上为本人题解和代码
边栏推荐
猜你喜欢
【自】-刷题-峰值
这款全网热评的无线路由器,到底有什么特别?
Pin mapping relationship of stm32f103c series single chip microcomputer under Arduino framework
新一代超安全蜂窝电池 思皓爱跑上市13.99万元起售
Rhce第二天
二舅火了,全网刷屏,他凭什么能治好我的精神内耗?
超参数优化(网格搜索和贝叶斯优化)
Zero vision technology completed the pre-A round of financing and promoted the domestic replacement of intelligent driving platform software
Arduino uno driver universe 1.8 'TFT SPI screen example demonstration (including data package)
CV目标检测模型小抄(2)
随机推荐
Byte 8 years' experience of female test Director - for girls who want to change careers or are about to enter the testing industry
ACM SIGIR 2022 | 美团技术团队精选论文解读
22 Niuke multi school Day1 I - Introduction to chiitoitsu DP
Codeforces Round #810 (Div. 2) A - C
1314_串口技术_RS232通信基础的信息
KingbaseES客户端编程接口指南-ODBC(4. 创建数据源)
金仓数据库 KingbaseES 与 Oracle 的兼容性说明(3. 常用函数)
mongodb索引添加、查看、导出、删除
2022g3 boiler water treatment test simulation 100 questions simulation test platform operation
可视化全链路日志追踪
Binary search tree
互动滑轨屏在展厅中应用的制作步骤
Form label
Pin mapping relationship of stm32f103c series single chip microcomputer under Arduino framework
Optimization and implementation of custom MVC
JS small method
Shenkaihong: on the river of Zhilian of all things, there is a bright moon of open source
MySQL functions
Win11快捷复制粘贴不能用怎么办?Win11快捷复制粘贴不能用
电脑不知卸载什么,打不开计算器无法编辑截图功能打不开txt文件等等解决方案之一