25. Reverse Nodes in k-Group
来源:互联网 发布:linuxmint优化 编辑:程序博客网 时间:2024/05/29 17:39
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 {public ListNode reverseKGroup(ListNode head, int k) {if (isValidSection(head, k) == false)return head;ListNode cur = head;ListNode prev = null, next = null;ListNode temp = cur;int count = k;//用next一个一个的去读取原链表,用prev去读取数据重新生成一个链表while (count > 0) {next = cur.next;cur.next = prev;prev = cur;cur = next;count--;}temp.next = reverseKGroup(cur, k);//递归return prev;}//由于题目是重复进行某个动作,肯定要用递归,输入数据的判断跟后面递归做的判断相似,就写成一个方法//k比ListNode的个数小,则返回false,否则truepublic static boolean isValidSection(ListNode node, int k) {ListNode cur = node;while (cur != null && k > 0) {cur = cur.next;k--;}if (k > 0)return false;return true;}}
0 0
- [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
- 25. Reverse Nodes in k-Group
- LeetCode 4.1.3 Largest Rectangle in Histogram
- 转: 母函数 入门 + 模板
- 生物力学仿真软件Anybody
- lintcode: Data Stream Median
- 移动互联的“大熊猫”——优秀前端工程师
- 25. Reverse Nodes in k-Group
- c++ const
- Web开发之二:什么是前端、什么是后端
- POJ 3641 Pseudoprime numbers【素数+快速幂】
- Android studio 引用系jar包的问题
- Android解析之三分钟教你快速掌握并使用GSON解析Json
- Linux下python升级至2.7步骤
- [蓝桥杯]第四届c/c++B组决赛 高僧斗法
- 12-Add Digits