# 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

// set the initial length to 1
int length = 1;
// set the tail to the 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

// loop while length is greater than k
while (length > k) {
// decrement the length
length --;
}

// set the next item on tail to null
newTail.next = null;

// set the tail's next item to head
``` ```
``` ```
``` ```
``` ```
``` ```
``` Privacy Policy Copyright © 2009 - 2024 Ataiva.com "serviceWorker"in navigator&&navigator.serviceWorker.register("/service-worker.js") !function(){const e=document.createElement("script");e.async=!0,e.setAttribute("crossorigin","anonymous"),e.src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1126602015214222";let t=0;document.addEventListener("mousemove",function(){1==++t&&document.getElementsByTagName("HEAD").item(0).appendChild(e)}),window.onscroll=function(){1==++t&&document.getElementsByTagName("HEAD").item(0).appendChild(e)},setTimeout(function(){0===t&&(t++,document.getElementsByTagName("HEAD").item(0).appendChild(e))},5e3)}(),(adsbygoogle=window.adsbygoogle||[]).push({}) ```