Given a list, rotate the list to the right by K places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLAnd k =2,
Return4->5->1->2->3->NULL.
Solution:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head==null||head.next==null || n==0) return head; ListNode fakeHead = new ListNode(0); fakeHead.next=head; int length=0; ListNode start=fakeHead, end=fakeHead; for(int i=0; i<n; i++){ if(end.next==null) break; end=end.next; length++; } if(end.next==null){ //when n>=length //int startPos = (length-n)%length+length; //Or: int startPos=n%length; if(startPos==0) return fakeHead.next; startPos=length-startPos; for(int i=0; i<startPos; i++){ start=start.next; } } else{ while(end.next!=null){ start=start.next; end=end.next; } } //reorder list end.next=fakeHead.next; fakeHead.next=start.next; start.next=null; return fakeHead.next; }}NOTE: If end. Next is not null after the end is shifted n times, the length of the list is greater than N. Then start and end are moved back.
Otherwise, the length of the list is <= n, and the actual number of rotate times must be found at this time. For a long list, if the number of rotate is length, the result is the original list. Therefore, the actual number of Rotate operations is n % length. If the result is 0, the original list is directly returned. Otherwise, the corresponding start point must be found, that is, the starting point of the list change.
Note:
int startPos = (length-n)%length+length;
Actually and
int startPos=n%length;startPos=length-startPos;
One effect (when startpos is not 0 ). However, the latter is easier to understand than the hacker.
The modulo of another negative number to a positive number is calculated as follows:
Result = m % n, where M <= 0, N> 0
Assume M = xn + result, where x <= 0, result <0 and-result <n.
For example (-5) % 3. -5 = 3 * (-1) + (-2 ). So (-5) % 3 =-2.
22nd question rotate list