25. Reverse Nodes in k-Group (JAVA)
2024-10-01 20:04:16
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of kthen left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(k == 1) return head; ListNode cur = head;
ListNode curHead = head; //head of current subgroup
ListNode nextHead = head; //head of next subgroup
ListNode preTail = null; //tail of previous subgroup
while(true){
//check whether there's enough elements in subgroup
for(int i = 1; i < k; i++){
if(cur == null) break; //not enough element in subgroup
cur = cur.next;
}
if(cur == null) break; //not enough element in subgroup //reverse nodes
cur = curHead.next;
for(int i = 1; i < k; i++){
nextHead = cur.next;
if(preTail==null) {
cur.next = head;
head = cur;
}
else {
cur.next = preTail.next;
preTail.next = cur;
}
cur = nextHead;
}
curHead.next = nextHead;
preTail = curHead;
curHead = nextHead; }
return head;
}
}
因为while语句是无条件循环,特别要注意k==1时的死循环。
最新文章
- SVG学习备忘录
- JVM之Parallel Old收集器
- ThreadLocal原理及其实际应用
- 启动Eclipse弹出:Failed to load JavaHL Library 错误框的解决办法
- Python 时间和日期模块的常用例子
- 黑盒测试用例设计方法&;理论结合实际 ->; 等价类划分
- 补充:学会Twitter Bootstrap不再难
- Python---十年语言之首
- UIImageView中最容易用错的属性UIContentMode小记
- Microsoft Fakes进行单元测试
- 剑指offer编程题Java实现——面试题11数值的整数次方
- 基于 Vue.js 的移动端组件库mint-ui实现无限滚动加载更多
- ie8兼容性总结
- 数据可视化 seaborn绘图(1)
- Linux初级入门(第一次作业)
- ZooKeeper 典型的应用场景——及编程实现
- 安装架设Apache+MySQL+PHP网站环境
- LeetCode题解之 Sum of Left Leaves
- Img与background的区别
- WPF在XAML的资源中定义空字符串String.Empty
热门文章
- Ubuntu 16.04安装Docker-CE
- 理解OpenShift(5):从 Docker Volume 到 OpenShift Persistent Volume
- 2016310Exp4 恶意代码及分析
- [WebService].net中WebService的使用实例
- linux git 保存账号密码
- [UnityShader效果]01.Mask
- Picasso, ImageLoader, Fresco, Glide 优劣
- MySQL使用LOAD DATA LOCAL INFILE报错
- windows快速搭建FTP工具Serv-U FTP Server
- pyqt------对话框