-
Notifications
You must be signed in to change notification settings - Fork 0
/
P38.java
48 lines (44 loc) · 1.33 KB
/
P38.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
import java.io.*;
import java.util.*;
/*************************************************************
*
* Following is the LinkedListNode class structure
*
* class LinkedListNode<T> {
* T data;
* LinkedListNode<T> next;
* LinkedListNode<T> random;
*
* public LinkedListNode(T data) {
* this.data = data;
* }
* }
*
*************************************************************/
public class P38 {
public static HashMap<LinkedListNode, LinkedListNode> hm = new HashMap();
public static LinkedListNode copy(LinkedListNode node) {
if (node == null)
return node;
if (!hm.containsKey(node)) {
LinkedListNode newNode = new LinkedListNode(node.data);
hm.put(node, newNode);
return newNode;
} else
return hm.get(node);
}
public static LinkedListNode<Integer> cloneRandomList(LinkedListNode<Integer> head) {
if (head == null)
return head;
LinkedListNode original_head = head;
LinkedListNode newhead = new LinkedListNode(head.data);
hm.put(original_head, newhead);
while (head != null) {
newhead.next = copy(head.next);
newhead.random = copy(head.random);
head = head.next;
newhead = newhead.next;
}
return hm.get(original_head);
}
}