Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
Given
1->2->3->4->5->NULL
and k = 2
,return
4->5->1->2->3->NULL
.
Solution 1: Just need to pay attention that K could be big than length of the list.
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head==null) return null;
ListNode i=head, j=head;
int count=0;
while (i!=null) {
count++;
i=i.next;
}
k=k%count;
if (k<=0) return head;
i=head;
while (k-->0 && i!=null) i=i.next;
if (i==null) return head;
while (i.next!=null) {
i=i.next;
j=j.next;
}
ListNode p=j.next;
j.next=null;
i.next=head;
return p;
}
}
没有评论:
发表评论