Intuition
Rotating a list of length n by k is the same as rotating by k % n. Once we know the length, we just need to find the new tail (at index n - k - 1) and rewire it.
Explanation
Approach
- Walk the list once to compute its length
n(and find the original tail). - Set
k = k % n. Ifk == 0, returnheadunchanged. - Walk to the node at position
n - k - 1— this becomes the new tail. - Its
nextis the new head. Set the original tail'snextto the old head, and the new tail'snexttoNone.
Edge cases
- Empty list or
k == 0: return as-is. klarger thann: the modulo handles it.
Complexity
- Time:
O(n)— two passes. - Space:
O(1)— pointer rewiring only.
Implementation
import java.util.*;
class Solution {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) return head;
int n = 1;
ListNode cur = head;
while (cur.next != null) {
n++;
cur = cur.next;
}
k = k % n;
if (k == 0) return head;
ListNode newTail = head;
for (int i = 0; i < n - k - 1; i++) {
newTail = newTail.next;
}
ListNode newHead = newTail.next;
newTail.next = null;
cur = newHead;
while (cur.next != null) {
cur = cur.next;
}
cur.next = head;
return newHead;
}
}