-
Notifications
You must be signed in to change notification settings - Fork 7
/
Main.java
42 lines (37 loc) · 1.02 KB
/
Main.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
package com.company;
import java.util.HashMap;
import java.util.Map;
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
public class Main {
public static void main(String[] args) {
// write your code here
}
public Node copyRandomList(Node head) {
Map<Node, Node> map = new HashMap<>();
Node cloneHead = copyNode(head, map);
Node point = head, clonePoint = cloneHead;
while (point != null){
clonePoint.next = copyNode(point.next, map);
clonePoint.random = copyNode(point.random, map);
point = point.next;
clonePoint = clonePoint.next;
}
return cloneHead;
}
public Node copyNode(Node node, Map<Node, Node> map){
if(node == null) return null;
if(map.containsKey(node)) return map.get(node);
Node clone = new Node(node.val);
map.put(node, clone);
return clone;
}
}