leetcode 25. Reverse Nodes in k-Group——很值得一看的链表题
2016-05-25 14:49
501 查看
//Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. //If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. //You may not alter the values in the nodes, only nodes itself may be changed. //Only constant memory is allowed. //For 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 public class Solution { static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public static void main(String[] args) { ListNode p = new ListNode(1); ListNode input = p; for(int i = 0;i<6;i++){ ListNode a = new ListNode(i+2); p.next = a; p = p.next; } ListNode result = reverseKGroup(input,3); while(result!=null){ System.out.println(result.val); result = result.next; } } public static ListNode reverseKGroup(ListNode head, int k) { if(head == null || k == 1) return head; ListNode dummy = new ListNode(0); //在当前链表之前创建一个结点 dummy.next = head; ListNode pre = dummy; //是pre,dummy都为链表之前的这个结点 int i = 0; while(head != null){ i++; if(i % k ==0){ //为k的整数倍 pre = reverse(pre, head.next); head = pre.next; //head永远为pre之后的那个结点 }else { head = head.next; //找到要逆序排列链表的最后一个结点 } } return dummy.next; //返回新建节点之后的链表 } //将当前链表除首尾结点外的结点进行逆序连接,输出与尾结点相连的前一个节点 private static ListNode reverse(ListNode pre, ListNode next){ //画图才能理解 ListNode last = pre.next; ListNode cur = last.next; while(cur != next){ last.next = cur.next; cur.next = pre.next; pre.next = cur; cur = last.next; } return last; } }
相关文章推荐
- Nodejs学习笔记(二)
- Nodejs学习笔记(一)
- node.js读取本地的文件
- nodejs的调试(node-inspector)
- node.js windows 64位安装
- 10个常见的Node.js面试题
- 10个常见的Node.js面试题
- requirejs in node
- "same tree" and "Delete Node in a Linked List"
- Promise.all解决异步条件的收敛
- 删除node_modules文件下依赖层次过多的解决方法
- 整理node中的变量
- leetcode 24. Swap Nodes in Pairs
- 《深入浅出nodeJS》学习笔记-第一章Node简介
- node.js简单服务器创建代码
- 51NOde+大数相乘+注意找规律
- Mac下配置Nodejs开发环境
- Windows部署LeanCloud本地命令行工具
- node.js实现微博系统在express3.0+版本下的实现——所遇问题
- nodejs遇到的问题