1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public ListNode rotateRight(ListNode head, int k) { ListNode tmp = head; int count = 0; ListNode end = null; while(tmp != null){ if(tmp.next == null){ end = tmp; } tmp = tmp.next; count++; }
if(count == 0){ return head; }
int i = k % count; int j = count - i - 1; tmp = head; while(j > 0){ tmp = tmp.next; j--; }
if(tmp.next != null){ ListNode result = tmp.next; tmp.next = null; end.next = head; return result; }else{ return head; } } }
|