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.

小细节容易写不好,cycle

public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head ==null) return null;
        ListNode  tmp = head;
        int len =1;
        while(tmp.next!=null){
            tmp = tmp.next;
            len++;
        }
        tmp.next = head;
        k = k%len;
        for(int i=0; i<len-k; i++){
            tmp = tmp.next;
        }
        ListNode nh = tmp.next;
        tmp.next = null;
        return nh;
        
    }
}

 

posted @ 2015-04-08 01:32  世界到处都是小星星  阅读(95)  评论(0编辑  收藏  举报