leetcode-25. Reverse Nodes in k-Group
来源:互联网 发布:ubuntu find file 编辑:程序博客网 时间:2024/05/20 17:58
leetcode-25. Reverse Nodes in k-Group
题目:
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->5For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
之前有一道24. Swap Nodes in Pairs
思路基本上一样,只是泛化一下:
首先,链表的题加哑节点基本上是通行的方法了
其次,判断一下是否有足够的节点来进行翻转,如果有则进行k个节点的翻转,如果没有则直接返回。
最后,翻转的时候和两节点的类似,需要建立k大小的数组来储存哑节点之后的k个需要翻转的节点,翻转之后移动哑节点到最后的一个翻转完成的节点的位置,然后迭代。
/** * 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) { ListNode d = new ListNode(0); ListNode ret = d; d.next = head; helper(d,k); return ret.next; } private ListNode helper(ListNode d, int k){ if(k<=1) return d; int t = k; ListNode p = d; while(p.next!=null){ p = p.next; if(--t==0) break; } if(t==0){ ListNode[] list = new ListNode[k]; ListNode tmp = d; for(int i = 0 ; i < k ; i++){ tmp = tmp.next; list[i] = tmp; } tmp = d; tmp.next = list[k-1]; list[0].next = list[k-1].next; for(int i = 1 ; i < k ; i++){ list[i].next = list[i-1]; } tmp = list[0]; helper(tmp,k); } return d; }}
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
- 【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
- 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
- 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
- leetcode 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- service和Activity之间的通信
- Docker学习1_CentOS6下docker的安装和使用
- ReactNativeUI渲染分析
- iOS button背景颜色状态设置
- C#超基础:继承与多态
- leetcode-25. Reverse Nodes in k-Group
- 微信JSSDK分享接口教程,wechat,share ,onMenuShareAppMessage wx.onMenuShareTimeline
- Spring MVC过滤器-字符集过滤器,解决中文乱码问题
- 大促流程
- 润乾报表怎样在tomcat7.0下部署demo应用(集算报表)
- plsql developer如何在窗口列表直接可以修改表格中的数据?
- java动态解析文本模板
- 容器云平台在企业中的落地实践
- laravea 添加 分层/嵌套 控制器 (方法二)