-
Notifications
You must be signed in to change notification settings - Fork 112
/
Solution.java
93 lines (71 loc) · 1.96 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
86
87
88
89
90
91
92
93
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Oleg Cherednik
* @since 01.02.2019
*/
public class Solution {
public static void main(String... args) {
test(5, 0); // [0, 1, 2, 3]
test(5, 1); // [0, 1, 2, 4]
test(5, 2); // [0, 1, 3, 4]
test(5, 3); // [0, 2, 3, 4]
test(5, 4); // [1, 2, 3, 4]
test(1, 0); // []
}
private static void test(int total, int k) {
Node root = createList(total);
System.out.println(print(root) + " -> " + print(remove(root, k)));
}
public static Node remove(Node root, int k) {
if (root == null)
return null;
int pos = 0;
Node prv = null;
Node node = root;
while (node != null) {
node = node.next;
pos++;
if (pos > k + 1)
prv = prv != null ? prv.next : root;
}
if (prv == null) {
node = root.next;
root.next = null;
return node;
}
node = prv.next.next;
prv.next = null;
prv.next = node;
return root;
}
private static final class Node {
private final int data;
private Node next;
public Node(int data) {
this.data = data;
}
}
private static Node createList(int total) {
Node root = null;
Node node = null;
for (int i = 0; i < total; i++) {
Node tmp = new Node(i);
if (node != null)
node.next = tmp;
node = tmp;
if (root == null)
root = tmp;
}
return root;
}
private static String print(Node node) {
List<Integer> values = new ArrayList<>();
while (node != null) {
values.add(node.data);
node = node.next;
}
return Arrays.toString(values.stream().mapToInt(val -> val).toArray());
}
}