-
Notifications
You must be signed in to change notification settings - Fork 112
/
Solution.java
85 lines (62 loc) · 1.72 KB
/
Solution.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* @author Oleg Cherednik
* @since 28.05.2019
*/
public class Solution {
public static void main(String... args) {
print(rotate(createList(8, 7, 3, 5), 2)); // 8 -> 7 -> 3 -> 5
print(rotate(createList(1, 2, 3, 4, 5), 3)); // 3 -> 4 -> 5 -> 1 -> 2
}
private static Node createList(int... arr) {
Node head = null;
Node node = null;
for (int val : arr) {
if (node == null)
node = new Node(val);
else {
node.next = new Node(val);
node = node.next;
}
if (head == null)
head = node;
}
return head;
}
private static void print(Node node) {
boolean first = false;
while (node != null) {
if (first)
System.out.print(" -> ");
System.out.print(node.val);
node = node.next;
first = true;
}
System.out.println();
}
public static Node rotate(Node head, int k) {
Node tail = getTail(head);
for (int i = 1; i <= k; i++) {
if (head.next == null)
throw new IllegalArgumentException();
Node next = head.next;
head.next = null;
tail.next = head;
head = next;
tail = tail.next;
}
return head;
}
private static Node getTail(Node node) {
Node tail = node;
while (tail.next != null)
tail = tail.next;
return tail;
}
public static final class Node {
public final int val;
public Node next;
public Node(int val) {
this.val = val;
}
}
}