LeetCode刷题笔录 Rotate List
2014-04-25 12:34
246 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
这题想法就是用两个pointer,一个比另外一个领先k个位置。对于上面那个例子,初始p1=1,p2=3;结束时p1=3,p2=5。
先扫描一遍链表,得到链表的长度,然后用k = n % length得到实际需要rotate的长度。
特殊情况:
1.list是空的
2.k=0
可以优化一下:
第一遍跑到尾巴得到长度以后,直接p2.next = head,把尾巴和头连起来,然后再跑length - k长度,把next设置成null即可。这样少了一次扫描,也不用考虑k=0的情况了。
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
这题想法就是用两个pointer,一个比另外一个领先k个位置。对于上面那个例子,初始p1=1,p2=3;结束时p1=3,p2=5。
先扫描一遍链表,得到链表的长度,然后用k = n % length得到实际需要rotate的长度。
特殊情况:
1.list是空的
2.k=0
public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head == null) return null; //get the length of the list ListNode p1 = head; int length = 1; while(p1.next != null){ length++; p1 = p1.next; } //get the rounded amount to rotate int k = n % length; //if k is zero, return as is if(k == 0) return head; //use two pointers with k distance p1 = head; ListNode p2 = head; for(int i = 0; i < k; i++){ p2 = p2.next; } while(p2.next != null){ p1 = p1.next; p2 = p2.next; } //the new head pointer is p1.next p2 = head; ListNode newHead = p1.next; p1.next = null; ListNode p3 = newHead; while(p3.next != null){ p3 = p3.next; } p3.next = p2; return newHead; } }
可以优化一下:
第一遍跑到尾巴得到长度以后,直接p2.next = head,把尾巴和头连起来,然后再跑length - k长度,把next设置成null即可。这样少了一次扫描,也不用考虑k=0的情况了。
相关文章推荐
- 【LeetCode】Rotate List 解题报告
- LeetCode 061. Rotate List
- LeetCode2.2.6(Rotate List)
- leetcode之Rotate List
- Leetcode Rotate List
- [LeetCode] 61. Rotate List
- leetcode - Rotate List
- Leetcode---Rotate List
- Rotate List -- LeetCode
- [LeetCode]61 Rotate List
- leetcode No61. Rotate List
- LeetCode:Rotate List
- leetcode---rotate-list---链表
- Leetcode——61. Rotate List
- LeetCode力扣之Rotate List
- 【leetcode】61. Rotate List【java】
- Rotate List leetcode java
- LeetCode-61-Rotate List 链表水题
- Leetcode: Rotate List
- LeetCode刷题笔录 Reorder List