Leetcode: Rotate List
This question, although not super common, is sometimes asked by Amazon, Bloomberg and LinkedIn. It is as follows:
Given the head of a linked list, rotate the list to the right by k places. Let's discuss an example.
Say that we want to rotate [1, 2, 3, 4, 5] to the right 2 places, then we would basically have [4, 5, 1, 2, 3] because the 5 is first moved, then the 4 is moved. My idea is to iterate through the list, find the number of elements, then the kth last element, and put these subsequent elements into the first element of the linked list.
Here's the approach.
We want to find the new head in position n - k, where n is the number of nodes in the list.
I had my own ideas, but the solution that Leetcode came up with is brilliant. We need to compute the number of nodes in the ring, and we need to break the ring after the new tail and just in front of the new head.
Now the new head is at n - k. The new tail would be at n - k - 1, or n - k % n - 1, an idea place to position the new tail at. Then make the final "new" tail next element null.
Here's the solution:
class Solution {
public ListNode rotateRight(ListNode head, int k) {
//return the original list if there is only 0 or 1 node.
if(head == null) return null;
if(head.next == null) return head;
ListNode old_tail = head;
int n;
//find the last element of the linked list and close it to a ring
for(n = 1; old_tail.next != null; n++){
old_tail = old_tail.next;
}
old_tail.next = head;
//find the new tail and the new head which would just be n - k % n - 1 and n - 1th node, or the point where the head is next to the tail.
ListNode new_tail = head;
//go n - k nodes to n - k - 1 to find the new tail
for(int i = 0; i < n - k % n - 1; i++) {
new_tail = new_tail.next;
}
ListNode new_head = new_tail.next;
//set the end of the tail and break the ring and return the new list
new_tail.next = null;
return new_head;
}
}



Comments
Post a Comment