-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
52 lines (49 loc) · 1.26 KB
/
Copy pathsolution.java
File metadata and controls
52 lines (49 loc) · 1.26 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
// 138. Copy List with Random Pointer
// https://leetcode.com/problems/copy-list-with-random-pointer/
// Medium | Java | Accepted 2025-11-08
// Runtime 0 ms | Memory 46.8 MB
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> nodeOldtoNew= new HashMap<>();
Node dummy = new Node(-1);
Node start = head;
Node headCopy = dummy;
while(start!=null)
{
Node newNode = new Node(start.val);
headCopy.next = newNode;
nodeOldtoNew.put(start, newNode);
headCopy = headCopy.next;
start = start.next;
}
Node through = head;
Node throughDum = dummy.next;
while(through!=null)
{
if(through.random==null)
{
throughDum.random = null;
}
else
{
throughDum.random = nodeOldtoNew.get(through.random);
}
through = through.next;
throughDum = throughDum.next;
}
return dummy.next;
}
}