当前位置:网站首页>链表中的节点每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;
}
};
边栏推荐
- Detailed explanation of pod life cycle
- 2022中国3D视觉企业(引导定位、分拣场景)厂商名单
- 【日常训练】871. 最低加油次数
- Hdu3507 (slope DP entry)
- [AUTOSAR 11 communication related mechanism]
- 1.12 - Instructions
- 利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
- [AUTOSAR twelve mode management]
- In the first half of 2022, there are 10 worth seeing, and each sentence can bring you strength!
- kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
猜你喜欢

【AutoSAR 十二 模式管理】

Rk3568 development board evaluation (II): development environment construction

【AutoSAR 十 IO架构】

Illustrated network: what is virtual router redundancy protocol VRRP?

如何系统学习机器学习

1.11 - 总线

【AutoSAR 九 C/S原理架构】
![[AUTOSAR XIII NVM]](/img/38/805ab70f199e2cfad4d9dae0e2c1ff.png)
[AUTOSAR XIII NVM]

2022中国3D视觉企业(引导定位、分拣场景)厂商名单
![[shutter] image component (the placeholder | transparent_image transparent image plug-in is loaded into the memory)](/img/73/19e2e0fc5ea6f05e34584ba40a452d.jpg)
[shutter] image component (the placeholder | transparent_image transparent image plug-in is loaded into the memory)
随机推荐
Vulkan is not a "panacea"“
解决ReactNative使用webView存在缓存问题
leetcode-241:为运算表达式设计优先级
[AUTOSAR eight OS]
【AutoSAR 九 C/S原理架构】
飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
matlab将数字矩阵保存为地理空间数据出错,显示下标索引必须为正整数类型或逻辑类型,解决
How to convert Quanzhi a40i/t3 to can through SPI
Test shift right: Elk practice of online quality monitoring
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
Leetcode-849: maximum distance to the nearest person
[AUTOSAR VI description document]
Overlay of shutter (Pop-Up)
世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud
全志A40i/T3如何通过SPI转CAN
[AUTOSAR twelve mode management]
leetcode-2280:表示一个折线图的最少线段数
[AUTOSAR II appl overview]
Array common operation methods sorting (including ES6) and detailed use