当前位置:网站首页>链表中的节点每k个一组翻转
链表中的节点每k个一组翻转
2022-07-03 00:29:00 【Schuyler Hu】
问题
将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。
思路
双指针确定反转区间,然后反转链表,返回新的头结点,原来的头结点经过反转后就变成了尾节点。每次递归调用,将 k 个节点反转,并返回反转过的新的头结点。
代码实现
/** * struct ListNode { * int val; * struct ListNode *next; * }; */
class Solution {
public:
/** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode* tail = head;
// 向前走 k 步,确定反转区间
for (int i = 0; i < k; i++)
{
if (!tail) return head;
tail = tail->next;
}
// 区间反转,返回新的头节点
ListNode* newHead = reverse(head, tail);
// 经过反转 head 变成 尾节点
head->next = reverseKGroup(tail, k);
return newHead;
}
ListNode* reverse(ListNode* head, ListNode* tail)
{
ListNode* pre = NULL;
ListNode* cur = head;
// 链表反转,返回 tail 前一个节点
while (cur != tail)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
边栏推荐
- (C语言)数据的存储
- 【AutoSAR 一 概述】
- Reading and writing speed of Reza rz/g2l arm development board storage and network measurement
- How to find out the currently running version of Solr- How do I find out version of currently running Solr?
- Attributeerror: 'tuple' object has no attribute 'layer' problem solving
- 文件操作IO-Part2
- leetcode-849:到最近的人的最大距离
- 【AutoSAR 四 BSW概述】
- Leetcode-871: minimum refueling times
- [AUTOSAR VI description document]
猜你喜欢

【AutoSAR 十一 通信相关机制】

Thank you for being together for these extraordinary two years!

AEM: Nanlin fan Ben et al. - plant rhizosphere growth promoting bacteria control soybean blight

Rk3568 development board evaluation (II): development environment construction

瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南
![[shutter] image component (cached_network_image network image caching plug-in)](/img/cc/967ff62c7f82e1c6613b3d0f26bb3e.gif)
[shutter] image component (cached_network_image network image caching plug-in)

1.11 - bus

Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
![[overview of AUTOSAR three RTE]](/img/6a/0df33beb42f165af77a17b5d8b01e2.png)
[overview of AUTOSAR three RTE]

【AutoSAR 十二 模式管理】
随机推荐
Tensorflow 2.x(keras)源码详解之第十五章:迁移学习与微调
这不平凡的两年,感谢我们一直在一起!
深度剖析数据在内存中的存储
【AutoSAR 十 IO架构】
1.12 - 指令
Leetcode-1964: find the longest effective obstacle race route to each position
Set up nacos2 X cluster steps and problems encountered
Leetcode 294. Flip game II (game theory)
Leetcode-2115: find all the dishes that can be made from the given raw materials
lex && yacc && bison && flex 配置的問題
How to systematically learn machine learning
[AUTOSAR + IO Architecture]
[shutter] image component (the placeholder | transparent_image transparent image plug-in is loaded into the memory)
File operation io-part2
Machine learning: numpy version linear regression predicts Boston house prices
文件操作IO-Part2
【AutoSAR 八 OS】
Overlay of shutter (Pop-Up)
Sentry developer contribution Guide - configure pycharm
图解网络:什么是虚拟路由器冗余协议 VRRP?