-
Notifications
You must be signed in to change notification settings - Fork 6
/
CopyListWithRandomPointer.java
64 lines (44 loc) · 1.31 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.shivaprasad.january.day19;
import java.util.HashMap;
//Note: For Linked List problems, Just focus on method code because creating Linked List for every problem is a hectic task,
//and we don't need to worry about it.
//Problem Link: https://leetcode.com/problems/copy-list-with-random-pointer/
public class CopyListWithRandomPointer {
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 null;
Node dummyNode = new Node(-10001);
Node r = dummyNode;
HashMap<Node,Node> map = new HashMap<>();
Node curr = head;
while(curr != null){
Node newNode = new Node(curr.val);
map.put(curr,newNode);
r.next = newNode;
r = newNode;
curr = curr.next;
}
r = dummyNode.next;
curr = head;
while(curr != null){
if(curr.random != null){
r.random = map.get(curr.random);
}
curr = curr.next;
r = r.next;
}
return dummyNode.next;
//T.C: O(n)
//S.C: O(n)
}
}