当前位置:网站首页>链表中的节点每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;
}
};
边栏推荐
- [Luogu p4320] road meets (round square tree)
- leetcode-849:到最近的人的最大距离
- University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
- Rust字符串切片、结构体和枚举类
- Nc17059 queue Q
- The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
- 飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
- 465. 最优账单平衡 DFS 回溯
- Sentry developer contribution Guide - configure pycharm
- Extension of flutter
猜你喜欢
数学建模之线性规划(含MATLAB代码)
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
Linux Software: how to install redis service
tail -f 、tail -F、tailf的区别
[AUTOSAR I overview]
【AutoSAR 十 IO架构】
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
详解RDD基本概念、RDD五大属性
【AutoSAR 十三 NVM】
File operation io-part2
随机推荐
Rust所有权(非常重要)
Arduino开发之按键检测与正弦信号输出
matlab将数字矩阵保存为地理空间数据出错,显示下标索引必须为正整数类型或逻辑类型,解决
【JetCache】JetCache的配置说明和注解属性说明
1.12 - Instructions
First hand evaluation of Reza electronics rz/g2l development board
【爱死机】《吉巴罗》被忽略的细节
1.11 - bus
Deep analysis of data storage in memory
Understanding and distinguishing of some noun concepts in adjustment / filtering
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
Leetcode-2280: represents the minimum number of line segments of a line graph
数据分析思维分析犯法和业务知识——分析方法(一)
【AutoSAR 七 工具链简介】
Thread start and priority
Solve the cache problem of reactnative using WebView
Infrared thermography temperature detection system based on arm rk3568
Set up nacos2 X cluster steps and problems encountered
测试右移:线上质量监控 ELK 实战
Key detection and sinusoidal signal output developed by Arduino