-
Notifications
You must be signed in to change notification settings - Fork 6
/
CopyListWithRandomPointer.java
43 lines (41 loc) · 1.04 KB
/
CopyListWithRandomPointer.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
package io.ziheng.list.leetcode;
import java.util.Map;
import java.util.HashMap;
/**
* LeetCode 138. Copy List with Random Pointer
* https://leetcode.com/problems/copy-list-with-random-pointer/
*/
public class CopyListWithRandomPointer {
private class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
public Node copyRandomList(Node head) {
if (head == null) {
return head;
}
Map<Node, Node> map = new HashMap<>();
Node node = head;
/**
* Node -> newNode
*/
while (node != null) {
map.put(node, new Node(node.val));
node = node.next;
}
node = head;
while (node != null) {
map.get(node).next = map.get(node.next);
map.get(node).random = map.get(node.random);
node = node.next;
}
return map.get(head);
}
}
/* EOF */