Skip to content

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
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
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; = next; } }
Code language: Java (java)

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 || == 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 ( != null) { // set the tail to the next item tail =; // increment the length length ++; } // set the amount of places to a remainer k %= length; // if none, then return the head if (k == ) 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 =; // decrement the length length --; } // set the next item on tail to null = null; // set the tail's next item to head = head; // return the new head return newHead; } }
Code language: Java (java)

See also  How to Fix: package org.junit.jupiter.api does not exist
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x