当前位置:网站首页>利用递归和链表头插法实现链表成组的翻转——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:以上为本人题解和代码
边栏推荐
猜你喜欢

Wechat applet development ③

Meet the outbreak period with the integration of transportation and parking, rush for mass production or build a technical moat?

Huawei wireless device configuration uses WDS technology to deploy WLAN services

2022起重机械指挥考试题模拟考试平台操作

LabVIEW对VISA Write和Read函数的异步和同步

如何将一个mongodb中集合的索引 添加到另一个mongodb中集合中

General addition, deletion, modification and query of custom MVC

2022t elevator repair examination questions and simulation examination

How to open a profitable gym? I tell you from one year's experience that don't fall in love

trivy【3】自定义扫描策略
随机推荐
In order for digital retail to continue to play its role, we need to give new connotation and significance to digital retail
行泊一体迎爆发期,抢量产还是修技术护城河?
ACM SIGIR 2022 | 美团技术团队精选论文解读
这款全网热评的无线路由器,到底有什么特别?
使用这个,你发的消息就无法被监控了
MySQL transaction and storage system
金仓数据库KingbaseES 客户端编程接口指南 - ODBC特性支持约束
被忽视的智能电视小程序领域
零视科技 H5S视频平台 GetUserInfo 信息泄漏漏洞 CNVD-2020-67113
Wechat applet development ③
以流量为主导的数字零售的发展模式,仅仅只是一个开始
Typescript class method this pointer binding
[self] - question brushing - string
Win11找不到DNS地址怎么办?Win11找不到DNS无法访问网页解决方法
22牛客多校day1 I - Chiitoitsu 概论dp
Shenkaihong: on the river of Zhilian of all things, there is a bright moon of open source
2022焊工(初级)上岗证题目及答案
How strong is this glue?
【自】-刷题-动态规划
Programmer growth Chapter 30: artifact of identifying true and false needs