LeetCode进阶之路(Reverse Nodes in k-Group)
2016-07-27 22:40
441 查看
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:
For k = 2, you should return:
For k = 3, you should return:
题目:给出一个链表和一个整数K,将链表以K个划分,并倒序,最后不满K个节点不变化位置。
思路:首先想到是将该链表以K个划分,并将每部分倒序后组合起来。一个链表倒序首先想到也是将节点放到数组里,这样就变的很熟悉,但是题目希望我们能熟悉链表指针,所以这里还是思考了使用指针来实现倒序的方法。
链表倒序:思路是每遍历一次,就把后一位移到第一位,直到完成。
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
题目:给出一个链表和一个整数K,将链表以K个划分,并倒序,最后不满K个节点不变化位置。
思路:首先想到是将该链表以K个划分,并将每部分倒序后组合起来。一个链表倒序首先想到也是将节点放到数组里,这样就变的很熟悉,但是题目希望我们能熟悉链表指针,所以这里还是思考了使用指针来实现倒序的方法。
链表倒序:思路是每遍历一次,就把后一位移到第一位,直到完成。
public ListNode reverse(ListNode node) { ListNode p1,p2 = null; p1 = node; while(node.next != null) { p2 = node.next; node.next = p2.next; p2.next = p1; p1 = p2; } return p2; }遍历节点,按K个取值
public ListNode reverseKGroup(ListNode head, int k) { if(head == null) { return null; } if(head.next == null ||k==1) { return head; } ListNode p1 = head; ListNode p2 = new ListNode(-1); ListNode p = p2; while(p1 != null) { ListNode p4 = new ListNode(-2); ListNode p3 = p4; int count = 0; while(count < k) { //取出K个节点,倒序后放到p2链表 count++; p3.next = p1; p3 = p3.next; if(p1.next == null) {//最后一个节点时结束循环,若此时count < k,就直接加到p2后面;若count = k,则执行倒序后覆盖 p.next = p4.next; p1 = p1.next; break; } p1 = p1.next;//p1指针一步步往后遍历 } if(count == k) { p3.next = null;//k个节点之后置为null,只倒序K个节点。 p.next = reverse(p4.next); } while(p.next != null) { p = p.next;//每次加上k个节点,就把指针移到p2结尾,等待下一组节点 } } return p2.next; }
种一棵树最好的时间是十年前,其次是现在!
相关文章推荐
- Node.js GET/POST请求
- Node.js 文件操作
- Node.js安装及常用命令(Mac OS )
- JS, Node.js, npm简介
- Populating Next Right Pointers in Each Node
- node anyproxy ssi简易支持
- 《nodejs实战》一
- Nodejs 学习笔记
- 24. Swap Nodes in Pairs
- Node.js 全局对象
- 使用NodeJS调用Dubbo工程
- node.js中文资料导航
- Nodejs——搭建电影展台(grunt)配置
- Node.js exports 和 require 两个对象
- nodejs的后端字符串验证器-validator
- ClouderaManager启动NodeManager失败!报错Failed to initialize container executor
- ASP.NET 开发人员不必担心 Node 的五大理由
- Node.cluster
- NodeJs-- 新建项目实例
- 运行node.js 后台代码准备工作