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 36 37 38 39 40 41
|
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class { public ListNode rotateRight(ListNode head, int k) { if(head == null) return head; ListNode fakeHead = new ListNode(0); fakeHead.next = head; ListNode fast = fakeHead; ListNode slow = fakeHead; int len = 0; ListNode p = head; while(p != null) { p = p.next; len++; } k = k % len; for(int i = 0; i < k; i++) { fast = fast.next; } while(fast.next != null) { fast = fast.next; slow = slow.next; } fast.next = head; fakeHead.next = slow.next; slow.next = null; return fakeHead.next; } }
|
近期评论