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
| class Solution { public ListNode rotateRight(ListNode head, int k) { if (head == null || head.next == null || k == 0) return head;
int length = 0; ListNode temp = head; while (temp != null) { temp = temp.next; length++; }
k = k % length; if (k == 0) return head;
for (int i = 0; i < k; i++) { ListNode prev = null; ListNode curr = head;
while (curr.next != null) { prev = curr; curr = curr.next; }
prev.next = null; curr.next = head; head = curr; }
return head; } }
|