61. Rotate List
来源:互联网 发布:php彩票网站系统 编辑:程序博客网 时间:2024/04/20 05:54
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
.
My solution
public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next == null || k == 0){ return head; } ListNode dummy = new ListNode(-1); dummy.next = head; int count = 1; while(head.next != null){ head = head.next; count++; } if(count == k){ return dummy.next; } if(count < k){ k = k % count; } int count2 = 0; ListNode newHead = dummy; //First version didn't realize [1, 2] 2 /*ListNode newHead = dummy.next; while(newHead != null){ count2 ++; if(count2 == count - k){ break; } newHead = newHead.next; }*/ while(newHead != null){ if(count2 == count - k){ break; } newHead = newHead.next; count2 ++; } head.next = dummy.next; dummy.next = newHead.next; newHead.next = null; return dummy.next; }
Solution 2 Two pointer, more elegant solution.
public static ListNode rotateRight2(ListNode head, int k) { if(head == null || head.next == null){ return head; } ListNode dummy = new ListNode(-1); dummy.next = head; ListNode fast = dummy; ListNode slow = dummy; int i; for(i = 0; fast.next != null; i++){ fast = fast.next; } for(int j = 0; j < i - k % i; j++){ slow = slow.next; } fast.next = dummy.next; dummy.next = slow.next; slow.next = null; return dummy.next; }
Solution 3 No need to count the length of the linked list
https://leetcode.com/discuss/7687/anyone-solve-the-problem-without-counting-the-length-of-list
1. Make the linkedlist to a circle
2.Use two pointers, when the fast one reaches the end, then jump to the head
0 0
- [LeetCode]61.Rotate List
- 61. Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 克隆虚拟机后无法连接网络的问题
- Andriod-NotificationManager
- php信号量子进程编程
- Java:实现单链表的创建
- FTP服务基本搭建
- 61. Rotate List
- mysql主从复制
- 小知识点源码解析-STAGE由最后一个RDD确定并行度的源码解析
- C#文件搜索小程序
- Start
- android使用jre自带工具生成证书
- 《HTML+CSS基础课程》学习笔记二
- Wscript对象详解
- @date2016-3-22(软件工程男的日常)