Given the head
of a singly linked list, rotate the list to the right by k
places. Rotating the list means moving the last k
elements to the front of the list and shifting the existing elements to the right.
For example:
1 -> 2 -> 3 -> 4 -> 5
and k = 2
, the output should be 4 -> 5 -> 1 -> 2 -> 3
.0 -> 1 -> 2
and k = 4
, the output should be 2 -> 0 -> 1
(since rotating by 4 is the same as rotating by 1 in this case).Constraints:
[0, 500]
.k
can be any non-negative integer up to 2 * 10^9.Write a function that takes the head
of a linked list and an integer k
, and returns the new head
of the rotated list. Explain your approach and consider edge cases such as an empty list or when k
is larger than the list size.
Let's explore how to rotate a linked list to the right by k
places.
The brute force method involves repeatedly moving the last element to the front of the list k
times. This is straightforward but inefficient.
k
iterations:This approach modifies the list k
times, leading to high time complexity.
This method is highly inefficient for large values of k
.
A more efficient approach involves these steps:
k
is larger than the list's length.
k % length
to get the effective rotation value.(length - k - 1)
th node. Its next node will be the new head.null
.k
is zero, return the original list.k
is a multiple of the list length, no rotation is needed.public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
ListNode tail = head;
int length = 1;
while (tail.next != null) {
tail = tail.next;
length++;
}
k = k % length;
if (k == 0) {
return head;
}
ListNode newTail = head;
for (int i = 1; i < length - k; i++) {
newTail = newTail.next;
}
ListNode newHead = newTail.next;
newTail.next = null;
tail.next = head;
return newHead;
}
This approach minimizes the number of traversals, leading to better performance.