forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
100 lines (76 loc) · 2.61 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
94
95
96
97
98
99
100
import java.util.HashMap;
import java.util.Map;
/**
* @author Oleg Cherednik
* @since 13.02.2019
*/
public class Solution {
public static void main(String... args) {
Node head = createList();
print(head); // 1(4) -> 2(5) -> 3(1) -> 4(2) -> 5(3) -> 6(null)
Node resHead = deepCopy(head);
print(resHead); // 1(4) -> 2(5) -> 3(1) -> 4(2) -> 5(3) -> 6(null)
}
private static Node createList() {
// 1(4) -> 2(5) -> 3(1) -> 4(2) -> 5(3) -> 6(null)
Node one = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
Node six = new Node(6);
one.next = two;
one.rnd = four;
two.next = three;
two.rnd = five;
three.next = four;
three.rnd = one;
four.next = five;
four.rnd = two;
five.next = six;
five.rnd = three;
return one;
}
private static void print(Node node) {
StringBuilder buf = new StringBuilder();
while (node != null) {
if (buf.length() > 0)
buf.append(" -> ");
buf.append(node.data).append('(').append(node.rnd != null ? node.rnd.data : null).append(')');
node = node.next;
}
System.out.println(buf);
}
public static Node deepCopy(Node head) {
Map<Node, Node> mapOriginalCopy = new HashMap<>();
Node originalTail = head;
Node resHead = null;
Node resTail = null;
while (originalTail != null) {
if (!mapOriginalCopy.containsKey(originalTail))
mapOriginalCopy.put(originalTail, new Node(originalTail.data));
if (resTail != null) {
resTail.next = mapOriginalCopy.get(originalTail);
resTail = resTail.next;
} else
resTail = mapOriginalCopy.get(originalTail);
if (originalTail.rnd != null) {
if (!mapOriginalCopy.containsKey(originalTail.rnd))
mapOriginalCopy.put(originalTail.rnd, new Node(originalTail.rnd.data));
resTail.rnd = mapOriginalCopy.get(originalTail.rnd);
}
resHead = resHead == null ? resTail : resHead;
originalTail = originalTail.next;
}
mapOriginalCopy.clear();
return resHead;
}
private static final class Node {
private final int data;
private Node next;
private Node rnd;
public Node(int data) {
this.data = data;
}
}
}