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 42 43
| public class Problem61_rotateLinkedList {
public static ListNode rotateRight(ListNode head, int k) { if (head == null || head.next == null || k == 0) { return head; }
ListNode curr = head; int n = 1; while (curr.next != null) { n++; curr = curr.next; } int step = n - k % n; if (step == n) { return head; } curr.next = head; while (step-- > 0) { curr = curr.next; } ListNode ans = curr.next; curr.next = null; return ans; }
public static void main(String[] args) { ListNode test1 = Utils.makeListNode(new int[]{1, 2, 3, 4, 5}); System.out.println("[4,5,1,2,3] ?=" + Utils.printLinkedList(rotateRight(test1, 2)));
ListNode test2 = Utils.makeListNode(new int[]{0, 1, 2}); System.out.println("[2,0,1] ?=" + Utils.printLinkedList(rotateRight(test2, 4)));
ListNode test3 = Utils.makeListNode(new int[]{1, 2}); System.out.println("[2,1] ?=" + Utils.printLinkedList(rotateRight(test3, 1)));
ListNode test4 = Utils.makeListNode(new int[]{1, 2, 3}); System.out.println("[2,3,1] ?=" + Utils.printLinkedList(rotateRight(test4, 2000000000)));
ListNode test5 = Utils.makeListNode(new int[]{1, 2}); System.out.println("[1,2] ?=" + Utils.printLinkedList(rotateRight(test5, 2))); } }
|