How to Rotate a Singly Linked List in Java


The challenge

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

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
```

## The solution in Java code

The definition for our singly-linked lists

```
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; }
}
```

Our solution in Java code:

```
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        // catch edge cases and return the head otherwise
        if (head == null || head.next == null) return head;
        
        // set the initial length to 1
        int length = 1;
        // set the tail to the head
        ListNode tail = head;
        
        // while a next item exists
        while (tail.next != null) {
            // set the tail to the next item
            tail = tail.next;
            // increment the length
            length ++;
        }
        
        // set the amount of places to a remainer
        k %= length;
        // if none, then return the head
        if (k == 0) return head;
        
        // set our new head and tail
        ListNode newHead = head;
        ListNode newTail = head;
        
        // loop while length is greater than k
        while (length > k) {
            // set tail to head
            newTail = newHead;
            // set head to next head
            newHead = newHead.next;
            // decrement the length
            length --;
        }
        
        // set the next item on tail to null
        newTail.next = null;
        
        // set the tail's next item to head
        tail.next = head;
        
        // return the new head
        return newHead;
    }
}
```