1public ListNode rotateRight(ListNode head, int k) {
2 if (head == null || head.next == null) return head;
3
4 // Calculate the length of the list
5 int length = 1;
6 ListNode tail = head;
7 while (tail.next != null) {
8 tail = tail.next;
9 length++;
10 }
11
12 // Make the list circular
13 tail.next = head;
14
15 // Find the new head and tail
16 k = k % length;
17 int stepsToNewHead = length - k;
18 ListNode newTail = head;
19 for (int i = 0; i < stepsToNewHead - 1; i++) {
20 newTail = newTail.next;
21 }
22 ListNode newHead = newTail.next;
23 newTail.next = null;
24
25 return newHead;
26}