当前位置:网站首页>LeetCode 25. K 个一组翻转链表
LeetCode 25. K 个一组翻转链表
2022-08-10 11:09:00 【水菜笔】
原题网址:https://leetcode.cn/problems/reverse-nodes-in-k-group/submissions/
给一个链表,一个k值,要求每k个节点为一组,进行翻转,不足k的不用管;
// 每k个节点是一组,对这组的节点进行翻转。
// 如果不够k个,就不用翻转了。
public ListNode reverseKGroup(ListNode head, int k) {
// 需要设置一个虚拟节点
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode node = dummyHead;
ListNode frist = head;
ListNode tail = head;
ListNode cur = head;
while(cur != null) {
for(int i=0;i<k-1;i++) {
tail = tail.next;
if(tail == null) {
return dummyHead.next;
}
}
// 截取k个节点,断开
ListNode next = tail.next;
tail.next = null;
node.next = null;
// 翻转
ListNode result = reverseList(frist);
frist.next= next;
node.next = tail;
node = frist;
cur = next;
frist = cur;
tail = cur;
}
return dummyHead.next;
}
private ListNode reverseList(ListNode head) {
ListNode first= null;
ListNode cur = head;
while(cur != null) {
ListNode next = cur.next;
cur.next = first;
first = cur;
cur = next;
}
return first;
}
边栏推荐
猜你喜欢
Analysis of the implementation principle of UUID from the perspective of source code
3款不同类型的自媒体免费工具,有效提高创作、运营效率
StoneDB Document Bug Hunting Season 1
模块九 - 设计电商秒杀系统
rider内Mono脚本找不到引用资源
【勇敢饭饭,不怕刷题之链表】链表反转的几种情况
AUTOCAD - reducing spline curve control points, the advanced CAD practice (3)
Since the media hot style title how to write?Taught you how to write the title
【勇敢饭饭,不怕刷题之链表】链表倒数节点问题
Open Office XML 格式里如何描述多段具有不同字体设置的段落
随机推荐
LeetCode50天刷题计划(Day 17—— 下一个序列(14.50-16.30)
[Go WebSocket] 多房间的聊天室(一)思考篇
电脑怎么设置屏幕息屏时间(日常使用分享)
LeetCode 82. 删除排序链表中的重复元素 II
Module 9 - Designing an e-commerce seckill system
StoneDB Document Bug Hunting Season 1
【勇敢饭饭,不怕刷题之链表】链表倒数节点问题
HDU 4135:Co-prime (容斥原理)
Analysis of the implementation principle of UUID from the perspective of source code
【小程序 | 启航篇】一文打通任督二脉
【勇敢饭饭,不怕刷题之链表】链表中有环的问题
从产品角度看 L2 应用:为什么说这是一个游乐场?
一文带你搞懂中断按键驱动程序之poll机制
第二十二章 源代码文件 REST API 参考(四)
LeetCode 61. 旋转链表
使用哈工大LTP测试分词并且增加自定义字典
LeetCode 445. 两数相加 II
【勇敢饭饭,不怕刷题之链表】有序链表的合并
Alibaba最新神作!耗时182天肝出来1015页分布式全栈手册太香了
三个绘图工具类详解Paint(画笔)Canvas(画布)Path(路径)