forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
69 lines (69 loc) · 2.04 KB
/
Solution.java
File metadata and controls
69 lines (69 loc) · 2.04 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
60
61
62
63
64
65
66
67
68
69
import java.util.*;
class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) {
this.label = x;
}
};
public class Solution {
/**
* solution 2
* @param head [description]
* @return [description]
*/
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return null;
}
// copy all nodes and insert in list
RandomListNode p = head;
while (p != null) {
RandomListNode e = new RandomListNode(p.label);
e.next = p.next;
p.next = e;
p = e.next;
}
// link the random pointer for copied
p = head;
while (p != null) {
if (p.random != null) p.next.random = p.random.next;
p = p.next.next;
}
// separate the copied to a new list
p = head;
RandomListNode ret = head.next, pp = head.next;
while (p != null) {
p.next = p.next.next;
if (p.next != null) pp.next = pp.next.next;
p = p.next;
pp = pp.next;
}
return ret;
}
public RandomListNode copyRandomListSolution1(RandomListNode head) {
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode ret = new RandomListNode(0);
ret.next = null;
RandomListNode currNew = ret, curr = head;
while (curr != null) {
currNew.next = new RandomListNode(curr.label);
map.put(curr, currNew.next);
currNew = currNew.next;
curr = curr.next;
}
currNew = ret.next;
curr = head;
while (curr != null) {
currNew.random = map.get(curr.random);
currNew = currNew.next;
curr = curr.next;
}
return ret.next;
}
public static void main(String[] args) {
Solution s = new Solution();
RandomListNode e = new RandomListNode(-1);
s.copyRandomList(e);
}
}