标签:
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; }
Java for LeetCode 061 Rotate List
标签:
原文地址:http://www.cnblogs.com/tonyluis/p/4506869.html