Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
Solution:
It is possible that K > num of nodes.
First try: connect all nodes:1->2->3->4->5->1->2->3->4->5.... complicated.
Second try: notice that after rotating (num of nodes) times, the list would be the same. (point!!!!!)
So K = K mod (num of nodes).
Given
1->2->3->4->5->NULL and k = 2,return
4->5->1->2->3->NULL.Solution:
It is possible that K > num of nodes.
First try: connect all nodes:1->2->3->4->5->1->2->3->4->5.... complicated.
Second try: notice that after rotating (num of nodes) times, the list would be the same. (point!!!!!)
So K = K mod (num of nodes).
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
// count the number of nodes in the list
int count = 0;
ListNode node = head;
while(node != null){
count++;
node = node.next;
}
if(count == 0)
return null;
n = n % count;
ListNode slow = head;
ListNode fast = head;
// fast is n steps ahead
while(n > 0){
n--;
fast = fast.next;
}
while(fast.next != null){
slow = slow.next;
fast = fast.next;
}
fast.next = head;
ListNode nt = slow.next;
slow.next = null;
return nt;
}
}

No comments:
Post a Comment