当前位置:网站首页>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;
}
边栏推荐
- A little self-deprecating deconstruction about farmers "code"
- LeetCode 92. 反转链表 II
- L2 applications from a product perspective: why is it a playground?
- mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded
- 微信小程序提交审核历史版本记录从哪里查看
- ViT结构详解(附pytorch代码)
- std::move()
- A case of violent parameter tuning in machine learning
- 不止跑路,拯救误操作rm -rf /*的小伙儿
- The brave rice rice, does not fear the brush list of 】 list has a ring
猜你喜欢
随机推荐
Some tips for using Unsafe
[Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
AUTOCAD - reducing spline curve control points, the advanced CAD practice (3)
【小程序 | 启航篇】一文打通任督二脉
使用哈工大LTP测试分词并且增加自定义字典
3款不同类型的自媒体免费工具,有效提高创作、运营效率
推荐6个自媒体领域,轻松易上手
Emulate stm32 directly with proteus - the programmer can be completely discarded
从产品角度看 L2 应用:为什么说这是一个游乐场?
为什么Redis很快
暑期总结4
基于UiAutomator2+PageObject模式开展APP自动化测试实战
Centos7环境使用Mysql离线安装包安装Mysql5.7
力扣练习—— 矩形区域不超过 K 的最大数值和(hard)
软件架构简介
AUTOCAD——减少样条曲线控制点数、CAD进阶练习(三)
Since the media hot style title how to write?Taught you how to write the title
十年架构五年生活-09 五年之约如期而至
力扣练习——64 最长和谐子序列
力扣练习——62 有效的数独