Given the head of a linked list, rotate the list to the right by k
places.
head = [1,2,3,4,5]
, k = 2
[4,5,1,2,3]
k
is 0?
k
always a positive integer?
k
can be 0 or any non-negative integer.k
?
k
can be larger than the length of the list, we will rotate it k % len(list)
times as rotating a list with its length results in the same list.k % length
.length - (k % length) - 1
.class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class RotateList {
public ListNode rotateRight(ListNode head, int k) {
// Edge case: empty list
if (head == null || head.next == null || k == 0) return head;
// Determine the length of the list
ListNode oldTail = head;
int length = 1;
while (oldTail.next != null) {
oldTail = oldTail.next;
length++;
}
// Create a circular list
oldTail.next = head;
// Effective rotations needed
k = k % length;
int newTailPos = length - k - 1;
// Find the new tail
ListNode newTail = head;
for (int i = 0; i < newTailPos; i++) {
newTail = newTail.next;
}
// Find the new head
ListNode newHead = newTail.next;
// Break the circle
newTail.next = null;
return newHead;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?