Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head == null) return head; ListNode run = head; int sum = 0; while(run!=null){ run = run.next; sum++; } n = n % sum; if (n== 0) return head; run = head; while(run.next != null){ run = run.next; } n = sum - n; ListNode tail = head; run.next = head; while(n-->1){ tail = tail.next; } head = tail.next; tail.next = null; return head; } }
mistake: tail has to be distance 1 from new head
public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head == null) return head; ListNode run = head; int sum = 0; while(run!=null){ run = run.next; sum++; } n = n % sum; if (n== 0) return head; run = head; while(run.next != null){ run = run.next; } n = sum - n; run.next = head; while(n-->1){ head = head.next; } ListNode tail = head; head= head.next; tail.next = null; return head; } }