LeetCode进阶之路(Reverse Nodes in k-Group)
来源:互联网 发布:交叉熵 圣经网络 编辑:程序博客网 时间:2024/06/08 23:54
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
题目:给出一个链表和一个整数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; }
0 0
- LeetCode进阶之路(Reverse Nodes in k-Group)
- LeetCode之Reverse Nodes in k-Group
- leetcode之Reverse Nodes in k-Group
- LeetCode之Reverse Nodes in k-Group
- 【Leetcode】之Reverse Nodes in k-Group
- leetcode之Reverse Nodes in k-Group
- leetcode之Partition List,Reverse Nodes in k-Group
- LeetCode 之 Reverse Nodes in k-Group — C 实现
- Leetcode之Reverse Nodes in k-Group (Hard)
- LeetCode第25题之Reverse Nodes in k-Group
- LeetCode:Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group
- LeetCode : Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- [Leetcode] reverse nodes in K-Group
- [LeetCode]Reverse Nodes in k-Group
- LeetCode-Reverse Nodes in k-Group
- LeetCode - Reverse Nodes in k-Group
- Quartz2D-基本图形绘制
- HDU 1166 敌兵布阵 数据结构+树状数组+(单点更新区间求和)
- 【android学习】断线重连机制
- windows svn使用别名 映射ip,出差时候就方便多了
- vs运行时出现的问题及其解决方法1.1——1.10
- LeetCode进阶之路(Reverse Nodes in k-Group)
- Java中的基本数据类型
- JAVA(七)java面向对象1-面向对象的概念,类与对象
- 算法竞赛入门经典3.3 数数字UVa1225
- (22)HTML标签详解之<img><map><area>
- 设计模式10_门面模式
- Mac 升级到El Capitan或者Yosemite出现用户级目录404 NOT FOUND的解决方案
- leetcode题解日练--2016.7.27
- Java第三天