# Rotate List

This is No.61 in leetcode.

The description:
Given a linked list, rotate the list to the right by k places, where k is non-negative.

This is my original solution:

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {

if (k == 0){
}

// cur -> 3
int count = 1;
while (count <= k && cur !=  null)
{
cur = cur.next;
count++;
}

if (cur == null){
}

ListNode tail = cur;

while(cur.next != null){
cur = cur.next;
}

/*
// tail -> 4
tail = cur.next;

// 1 - 2 - 3 - 4 - 5 - 1

//4 - 5 - 1 - 2 - 3
cur.next = NULL;
*/

tail.next = null;

}
}``````

It could pass some tests, but here is a wrong case when the k is greater than the length of list, for example:

``````Input
[0,1,2]
4
Output
[0,1,2]
Expected
[2,0,1]``````

Then I fix my code as below:

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {

if(head == null || k == 0) {
}

int len = 1;

while(cur.next != null) {
cur = cur.next;
len++;
}

k %= len;

for(int i = 0; i < len - k; i++) {
cur = cur.next;
}