How to Rotate a Singly Linked List in Java

1 min read 320 words

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

            
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Ai
API
Aws
C
C
Cdk
CLI
Css
Dsp
Eks
Ffi
Gcp
Git
Go
Iac
Ide
Iot
JWT
Llm
MAC
Ml
Npm
Php
Pip
S3
Seo
Sli
Slo
SQL
Sre
SSH
Ssl
Vpc
Wsl

Recent Posts