[leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
来源:互联网 发布:淘宝衣服拍摄 编辑:程序博客网 时间:2024/04/29 12:09
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=2 就是2个一组反转,反转后的点又指向了之后的节点,那么我们就知道了:
(1)首先得把链表的长度求出来 要是K=链表长度(len),那就是整个链表圈反转,要是小于,那我们只反转k个节点。
(2)反转了K个,那len-k个怎么办,我们可以想到用递归来求解,把剩下的节点扔到递归里,让它们自己算
那么递归的base case我们肯定要让head不为空,并且长度大于K,否则就返回null
每次都算长度太坑爹,肯定是一开始算好,把len当参数,给子问题。那么我们就可以再写一个带len(链表长度)的函数
(3)递归的细节
那我们最后返回的头应该是什么,肯定是第一次以K为单位反转的头,例如k=2 1->2->3->4->5,那么返回2->1->..
那么反转节点的末尾就是:子问题,长度为3的链表,依次类推
最后只剩下5一个点,传进函数后根据base case直接返回这个点就行
public class Solution { public ListNode reverseKGroup(ListNode head, int k) { return reverseK(head, k, getLength(head)); } public ListNode reverseK(ListNode head, int k, int len){ if(k==1 || k>len || head==null) return head; int i=2; ListNode next=head.next; ListNode pre=head; head.next=null; ListNode dummy=head; while(i<=k){ head=next; next=next.next; head.next=pre; pre=head; head=next; i++; } dummy.next=reverseK(head, k, len-k); return pre; } public int getLength(ListNode head){ int len=0; while(head!=null){ len++; head=head.next; } return len; }}
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- leetCode 25.Reverse Nodes in k-Group (以k个节点为一组反转链表) 解题思路和方法
- [LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序
- LeetCode 25 Reverse Nodes in k-Group K个一组反转节点
- leetcode:Reverse Nodes in k-Group(以k为循环节反转链表)【面试算法题】
- LeetCode | Reverse Nodes in k-Group(k个结点一组翻转链表)
- [LeetCode] Reverse Nodes in k-Group每k个一组翻转链表
- 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group(单链表中k个结点一组进行反转)】
- 链表编程题专题--Reverse Nodes in k-Group(最后几个节点不足一组的不逆序)
- LeetCode 25. Reverse Nodes in k-Group(反转链表)
- LeetCode Reverse Nodes in k-Group(单链表连续分段反转)
- 【leetcode 链表相关】Reverse Nodes in k-Group
- 以k个元素为一组反转单向链表
- 以k个元素为一组反转单向链表
- Reverse Nodes in k-Group k个数为一组翻转结点
- Reverse Nodes in k-Group k-group翻转链表@LeetCode
- 链表的部分逆转 Reverse Nodes in k-Group
- LeetCode:Reverse Nodes in k-Group
- SQL Server快捷键
- 安卓仿iphone日期选项器 仿iphone日期选择自定义控件
- Ubuntu 14.04.1 LTS上编译安装新的kernel
- A. Little Pony and Crystal Mine
- 习近平赢得人民信赖
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- 软件编程我该学习什么?
- 股份或幾乎覆蓋
- ios--视图的层次关系
- michael kors outlet xqhxrl yjm xjei
- cheap uggs yvgpso wqm nrmy
- cheap louis vuitton nyymqu yfo vdtg
- Python 正则表达式验证U.K.邮政编码
- FPGA开发之时钟管理模块