[leetcode]Rotate List

Rotate List

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.

算法思路:

注意处理边界情况,k > length,需要取余的,坑爹。k == 0 || length时,不作处理

 1 public class Solution {
 2     public ListNode rotateRight(ListNode head, int n) {
 3         ListNode hhead = new ListNode(0);
 4         hhead.next = head;
 5         ListNode tail = hhead;
 6         int length = 0;
 7         while(tail.next != null){
 8             length++;
 9             tail = tail.next;
10         }
11         if(length == 0 || n == 0) return head;
12         if(n >= length) n %= length;
13         ListNode pre = hhead;
14         for(int i = 0; i < length - n; pre = pre.next,i++);
15         tail.next = hhead.next;
16         hhead.next = pre.next;
17         pre.next = null;
18         return hhead.next;
19     }
20 }

posted on 2014-07-19 17:35  喵星人与汪星人  阅读(167)  评论(0编辑  收藏  举报