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可能大于链表的长度
代码如下(已通过leetcode)
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null||head.next==null) return head;
ListNode pre=head;
ListNode later=head;
int listsize=0;
ListNode temp=head;
while(temp!=null) {
listsize++;
temp=temp.next;
}
k=k%listsize;
while(k>0) {
later=later.next;
k--;
}
while(later.next!=null) {
pre=pre.next;
later=later.next;
}
later.next=head;
head=pre.next;
pre.next=null;
return head;
}
}