|
| 1 | +// https://leetcode.com/problems/rotate-list |
| 2 | +// T: O(N) |
| 3 | +// S: O(1) |
| 4 | + |
| 5 | +public class RotateList { |
| 6 | + public static class ListNode { |
| 7 | + int val; |
| 8 | + ListNode next; |
| 9 | + ListNode() {} |
| 10 | + ListNode(int val) { this.val = val; } |
| 11 | + ListNode(int val, ListNode next) { this.val = val; this.next = next; } |
| 12 | + } |
| 13 | + |
| 14 | + public ListNode rotateRight(ListNode head, int k) { |
| 15 | + final int length = getLength(head); |
| 16 | + if (length == 0) return head; |
| 17 | + final int rotations = k % length; |
| 18 | + if (rotations == 0) return head; |
| 19 | + final ListNode last = getLastNode(head); |
| 20 | + final ListNode cutoffNode = getCutoffNode(head, rotations, length); |
| 21 | + final ListNode newHead = cutoffNode.next; |
| 22 | + last.next = head; |
| 23 | + cutoffNode.next = null; |
| 24 | + return newHead; |
| 25 | + } |
| 26 | + |
| 27 | + private int getLength(ListNode head) { |
| 28 | + int length = 0; |
| 29 | + ListNode current = head; |
| 30 | + while (current != null) { |
| 31 | + current = current.next; |
| 32 | + length++; |
| 33 | + } |
| 34 | + return length; |
| 35 | + } |
| 36 | + |
| 37 | + private ListNode getLastNode(ListNode head) { |
| 38 | + ListNode current = head; |
| 39 | + while (current.next != null) { |
| 40 | + current = current.next; |
| 41 | + } |
| 42 | + return current; |
| 43 | + } |
| 44 | + |
| 45 | + private ListNode getCutoffNode(ListNode head, int rotations, int length) { |
| 46 | + ListNode current = head; |
| 47 | + for (int i = 0 ; i < length - rotations - 1 ; i++) { |
| 48 | + current = current.next; |
| 49 | + } |
| 50 | + return current; |
| 51 | + } |
| 52 | +} |
0 commit comments