25. Reverse Nodes in k-Group(23.53%)
来源:互联网 发布:哪些是淘宝禁售品 编辑:程序博客网 时间:2024/06/07 03:11
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,则直接返回。要求不能改变节点的值,要使用常量级内存。
依然是使用递归,这个是Swap Nodes in Pairs的升级版本,每一次做k个节点的倒序,我们都用一个长度为k+1的数组来记录节点并完成倒序操作。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (k < 2) { return head; } if (head == null) { return head; } ListNode judge = head; ListNode[] tempNodes = new ListNode[k+1]; for (int i = 0; i <= k; i++) { tempNodes[i] = judge; if (i == k) { break; } if (judge == null) { return head; } judge = judge.next; } tempNodes[0].next = reverseKGroup(tempNodes[k], k); for (int i = k-1; i >= 1;) { tempNodes[i].next = tempNodes[--i]; } return tempNodes[k-1]; }}
0 0
- 25. Reverse Nodes in k-Group(23.53%)
- [LeetCode]25.Reverse Nodes in k-Group
- LeetCode --- 25. Reverse Nodes in k-Group
- LeetCode 25.Reverse Nodes in k-Group
- [Leetcode] 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 【LeetCode】25.Reverse Nodes in k-Group
- [leetcode] 25.Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- Leetcode-25.Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- 通过Controller返回到jsp页面后,图片、css样式等消失了
- iOS扬声器和听筒模式的切换以及距离传感器红外感应的设置
- lintcode-螺旋矩阵 II
- activemq安全设置—设置admin的用户名和密码
- Error:Jack is required to support java 8 language features. Either enable Jack or remove sourceCompa
- 25. Reverse Nodes in k-Group(23.53%)
- EventBus使用详情、源码分析和注意事项
- 关于RemoteView的一点愚见(实现桌面小部件)
- 深入 HBase 架构解析(1)
- QtWebEngine打包时与众不同的地方
- Struct与class的区别
- JavaWeb商城系统项目记录(一)
- JavaScript强化教程——语句
- 国内游戏公司