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时的死循环。

最新文章

  1. SVG学习备忘录
  2. JVM之Parallel Old收集器
  3. ThreadLocal原理及其实际应用
  4. 启动Eclipse弹出:Failed to load JavaHL Library 错误框的解决办法
  5. Python 时间和日期模块的常用例子
  6. 黑盒测试用例设计方法&amp;理论结合实际 -&gt; 等价类划分
  7. 补充:学会Twitter Bootstrap不再难
  8. Python---十年语言之首
  9. UIImageView中最容易用错的属性UIContentMode小记
  10. Microsoft Fakes进行单元测试
  11. 剑指offer编程题Java实现——面试题11数值的整数次方
  12. 基于 Vue.js 的移动端组件库mint-ui实现无限滚动加载更多
  13. ie8兼容性总结
  14. 数据可视化 seaborn绘图(1)
  15. Linux初级入门(第一次作业)
  16. ZooKeeper 典型的应用场景——及编程实现
  17. 安装架设Apache+MySQL+PHP网站环境
  18. LeetCode题解之 Sum of Left Leaves
  19. Img与background的区别
  20. WPF在XAML的资源中定义空字符串String.Empty

热门文章

  1. Ubuntu 16.04安装Docker-CE
  2. 理解OpenShift(5):从 Docker Volume 到 OpenShift Persistent Volume
  3. 2016310Exp4 恶意代码及分析
  4. [WebService].net中WebService的使用实例
  5. linux git 保存账号密码
  6. [UnityShader效果]01.Mask
  7. Picasso, ImageLoader, Fresco, Glide 优劣
  8. MySQL使用LOAD DATA LOCAL INFILE报错
  9. windows快速搭建FTP工具Serv-U FTP Server
  10. pyqt------对话框