Java for LeetCode 061 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.

解题思路:

只需找到对应的位置,然后指向head,接着把之前节点指向null即可,注意k可以取大于length的值,所以k%=length,JAVA实现如下:

    public ListNode rotateRight(ListNode head, int k) {
    	if(head==null||head.next==null)
    		return head;
    	ListNode temp=head;
    	int length=1;
    	while(temp.next!=null){
    		temp=temp.next;
    		length++;
    	}
    	if(k==length)
    		return head;
    	temp.next=head;
    	temp=head;
    	for(int i=1;i<length-k;i++)
    		temp=temp.next;
    	head=temp.next;
    	temp.next=null;
        return head;
    }

 

posted @ 2015-05-15 21:21  TonyLuis  阅读(129)  评论(0编辑  收藏  举报