-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathCopyList.java
More file actions
50 lines (38 loc) · 1.06 KB
/
CopyList.java
File metadata and controls
50 lines (38 loc) · 1.06 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
package Hashing;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Author - archit.s
* Date - 30/10/18
* Time - 12:19 PM
*/
public class CopyList {
class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) { this.label = x; }
}
public RandomListNode copyRandomList(RandomListNode head) {
Map<RandomListNode, RandomListNode> map = new LinkedHashMap<>();
RandomListNode current = head;
while(current!=null){
map.put(current, new RandomListNode(current.label));
current = current.next;
}
RandomListNode newHead = null;
RandomListNode last = null;
for(RandomListNode t : map.keySet()){
if(newHead == null){
newHead = map.get(t);
last = map.get(t);
}
else{
last.next = map.get(t);
last = last.next;
}
last.random = map.get(t.random);
}
last.next = null;
return newHead;
}
}