-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathRotateLinkedList.java
71 lines (62 loc) · 1.62 KB
/
RotateLinkedList.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package by.andd3dfx.collections;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* <pre>
* <a href="https://leetcode.com/problems/rotate-list/">Task description</a>
*
* Given the head of a linked list, rotate the list to the right by k places.
*
* Example 1:
*
* Input: head = [1,2,3,4,5], k = 2
* Output: [4,5,1,2,3]
*
* Example 2:
*
* Input: head = [0,1,2], k = 4
* Output: [2,0,1]
* </pre>
*
* @see <a href="https://youtu.be/6tyflwO6PwY">Video solution</a>
*/
public class RotateLinkedList {
@Data
@AllArgsConstructor
public static class ListNode {
private int val;
private ListNode next;
@Override
public String toString() {
return "Node{v=%d}".formatted(val);
}
}
public static ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return null;
}
if (k == 0) {
return head;
}
var endItem = head;
var size = 1;
while (endItem.next != null) {
endItem = endItem.next;
size++; // measuring list size in background
}
endItem.next = head;
k %= size; // optimization: reduce amount of work
var curr = endItem;
int i = 0;
while (i < size - k) {
curr = curr.next;
i++;
}
var result = curr.next;
curr.next = null;
return result;
}
public static ListNode rotateLeft(ListNode head, int k) {
return rotateRight(head, -k);
}
}