LeetCode Reverse Nodes in k-Group(单链表连续分段反转)
2016-06-21 13:03
786 查看
题意:给出一个单链表及反转元素的个数,求反转后的单链表
思路:首先确定链表总结点数,根据反转元素的个数,可以知道要反转多少次。第一次反转的尾为新的单链表的头,而后序反转后的头变成前一次反转后发尾部元素的后继结点
具体代码如下:
思路:首先确定链表总结点数,根据反转元素的个数,可以知道要反转多少次。第一次反转的尾为新的单链表的头,而后序反转后的头变成前一次反转后发尾部元素的后继结点
具体代码如下:
public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (null == head || 0 == k || 1 == k) return head; int n = 0; ListNode cur = head; while (cur != null) { n++; cur = cur.next; } cur = head; int cnt = n / k, remainder = n % k; ListNode ans = null; ListNode tail = null; for (int i = 0; i < cnt; i++) { ListNode pre = null; ListNode tmp = cur; int c = 0; while (c++ < k) { ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } if (i != 0) { tail.next = pre; tail = tmp; } else { tail = tmp; ans = pre; } } if (remainder != 0) { if (tail != null) tail.next = cur; } if (null == ans) ans = head; return ans; }
相关文章推荐
- ROS学习--人脸识别NODE
- JetBrains使用技能分享征集大赛优秀作品——用webstorm开发NodeJS项目
- ROS学习--语义理解NODE(NLU,NLP)
- systemtap [主设备号,次设备好,inode]监控文件
- LeetCode OJ | #25 Reverse Nodes in k-Group
- nodejs的require模块及路径
- Nodejs的测试和测试驱动开发
- Node.js模块定义总结
- node环境
- node应用线上部署时锁定包的依赖版本
- Nodejs与Python脚本语言混编
- when 让你跳出异步回调噩梦 node.js下promise/A规范的使用
- node.js 下使用 util.inherits 来实现继承
- 使用node-livereload自动刷新页面
- nodejs 字符串转gbk base64
- Node.js 异步异常的处理与domain模块解析
- Nodejs-Koa是一个干净的框架
- 使用nodewebx进行前后端开发环境分离
- Nodejs学习之一 下载安装与部署nodejs
- NodeMCU教程 不断重启问题解决