[leetcode] Rotate List | 把后k个rotate到list前面去,k可以超过list本身长度
Posted by: lexigrey on: August 14, 2013
看别人思路:这个既然要rotate,不如先连起来loop,这样怎么也不怕null pointer exception了。然后再找到该断开的地方断开。
public ListNode rotateRight(ListNode head, int n) {
if (head == null || n == 0) return head; ListNode p = head; int len = 1;//since p is already point to head while (p.next != null) { len++; p = p.next; } p.next = head; //form a loop n = n % len; for (int i = 0; i < len - n; i++) { //len-n一画就出来了 p = p.next; } //now p points to the prev of the new head head = p.next; p.next = null; return head; }
Tags: list
Leave a Reply