当前位置:网站首页>LeetCode 25. A set of K flipped linked lists
LeetCode 25. A set of K flipped linked lists
2022-08-10 11:57:00 【Mizuna pen】
原题网址:https://leetcode.cn/problems/reverse-nodes-in-k-group/submissions/
给一个链表,一个k值,要求每k个节点为一组,进行翻转,不足k的不用管;
// 每knodes are a set of,Flip the nodes of this group.
// 如果不够k个,就不用翻转了.
public ListNode reverseKGroup(ListNode head, int k) {
// A virtual node needs to be set up
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;
}
边栏推荐
- 软件架构简介
- Apple bucks the trend and expands iPhone 14 series stocking, with a total of 95 million units
- 推荐6个自媒体领域,轻松易上手
- HDU 4135:Co-prime (容斥原理)
- ViT结构详解(附pytorch代码)
- LeetCode 86. 分隔链表
- LeetCode 92. 反转链表 II
- Since the media hot style title how to write?Taught you how to write the title
- 力扣练习——64 最长和谐子序列
- Nocalhost - Making development more efficient in the cloud-native era
猜你喜欢
随机推荐
HDU 4135: Co-prime (the principle of inclusion and exclusion)
使用.NET简单实现一个Redis的高性能克隆版(六)
LeetCode 109. 有序链表转换二叉搜索树
A case of violent parameter tuning in machine learning
Buckle exercise - rectangular area does not exceed the maximum value of K and (hard)
什么是幂等性?四种接口幂等性方案详解!
Analysis of the implementation principle of UUID from the perspective of source code
关于振弦采集模块及采集仪振弦频率值准确率的问题
实现内网穿透的最佳解决方案(无实名认证,完全免费)
A little self-deprecating deconstruction about farmers "code"
力扣练习——60 二叉搜索子树的最大键值和
力扣练习——61 根据字符出现频率排序
codevs 2370 Small room tree (LCA)
VSCode远程连接服务器报错:Could not establish connection to “xxxxxx”的可能错误原因及解决
建校仅11年就入选“双一流” ,这所高校是凭什么做到的?
SMIC CIM localization project suspended?Rising software: not shut down, changed to remote development!
AutoCAD Map 3D功能之一暴力处理悬挂点(延伸)
力扣练习——58 验证二叉搜索树
LeetCode 92. 反转链表 II
配置druid数据源「建议收藏」









