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
|
public class RotateList { public ListNode rotateRight(ListNode head, int k) { if (head == null || k == 0) { return head; } ListNode cursor = head; int l = 0; while (cursor != null) { l++; cursor = cursor.next; } k = k % l; if (k == 0) { return head; } int offSet = l - k; cursor = head; while (offSet > 1) { cursor = cursor.next; offSet--; } ListNode newHead = cursor.next; cursor.next = null; cursor = newHead; while (cursor.next != null) { cursor = cursor.next; } cursor.next = head; return newHead; } }
|