【leetcode】61. Rotate List【java】
来源:互联网 发布:linux查看时区 编辑:程序博客网 时间:2024/06/06 20:49
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
Since n may be a large number compared to the length of list. So we need to know the length of linked list.After that, move the list after the (l-n%l )th node to the front to finish the rotation.
Ex: {1,2,3} k=2 Move the list after the 1st node to the front
Ex: {1,2,3} k=5, In this case Move the list after (3-5%3=1)st node to the front.
So the code has three parts.
Get the length
Move to the (l-n%l)th node
3)Do the rotation
public ListNode rotateRight(ListNode head, int n) { if (head==null||head.next==null) return head; ListNode dummy=new ListNode(0); dummy.next=head; ListNode fast=dummy,slow=dummy; int i; for (i=0;fast.next!=null;i++)//Get the total length fast=fast.next; for (int j=i-n%i;j>0;j--) //Get the i-n%i th node slow=slow.next; fast.next=dummy.next; //Do the rotation dummy.next=slow.next; slow.next=null; return dummy.next;}
0 0
- (Java)LeetCode-61. Rotate List
- 【leetcode】61. Rotate List【java】
- [LeetCode] 61. Rotate List java
- [Leetcode] Rotate List (Java)
- [LeetCode][Java] Rotate List
- leetcode:Rotate List 【Java】
- Rotate List leetcode java
- [leetcode]61. Rotate List@Java解题报告
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- 利用Python,四步掌握机器学习
- Java Android HTTP实现总结
- Android应用实践-数独游戏
- [kpw] Kindle Paperwhite被强制升级到5.6.5后,USBNetwork无法使用
- Android - Activity的四种启动模式
- 【leetcode】61. Rotate List【java】
- [学习笔记]redis_windows之命令行之旅
- Fiddler使用总结。
- Spring中如何配置Hibernate事务
- nodejs搭建web服务教程
- 在eclipse中使用MyBatis Geneator自动生成出对应数据库的实体与映射文件
- ERP实施顾问岗位职责
- Redis Info 命令
- 30分钟掌握ES6核心内容(下)