-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138.copy-list-with-random-pointer.java
More file actions
59 lines (44 loc) · 1.09 KB
/
Copy path138.copy-list-with-random-pointer.java
File metadata and controls
59 lines (44 loc) · 1.09 KB
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
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
// @lc code=start
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
Map<Node, Node> map = new HashMap<>();
Node newHead = new Node(head.val);
map.put(head, newHead);
Node oldTemp = head.next;
Node newTemp = newHead;
while (oldTemp != null) {
Node copyNode = new Node(oldTemp.val);
map.put(oldTemp, copyNode);
newTemp.next = copyNode;
oldTemp = oldTemp.next;
newTemp = newTemp.next;
}
oldTemp = head;
newTemp = newHead;
while (oldTemp != null) {
newTemp.random = map.get(oldTemp.random);
oldTemp = oldTemp.next;
newTemp = newTemp.next;
}
return newHead;
}
}
// @lc code=end
/*
* @lc app=leetcode id=138 lang=java
*
* [138] Copy List with Random Pointer
*/