题目链接: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.
*
*/
public class RotateList {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
// 230 / 230 test cases passed.
// Status: Accepted
// Runtime: 245 ms
// Submitted: 0 minutes ago
public ListNode rotateRight(ListNode head, int n) {
if(head == null || n == 0) return head;
int len = 1;
ListNode cursor = head;
while(cursor.next != null) {
len ++;
cursor = cursor.next;
}
cursor.next = head;
n = len - n % len;
for (int i = 0; i < n; i++) {
cursor = cursor.next;
}
head = cursor.next;
cursor.next = null;
return head;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}