Skip to content

Commit cfb3196

Browse files
author
Li Li
committed
add code of 138
1 parent 79f592c commit cfb3196

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
1. generate new nodes and make the maping old -> new
3+
2. loop the old, use map to get all random and next.
4+
*/
5+
public class Solution {
6+
public RandomListNode CopyRandomList(RandomListNode head) {
7+
if (head == null) return null;
8+
Dictionary<RandomListNode, RandomListNode> dict = new Dictionary<RandomListNode,RandomListNode>();
9+
GenerateAllNodesAndMapping(head, dict);
10+
CopyList(head, dict);
11+
return dict[head];
12+
}
13+
private void GenerateAllNodesAndMapping(RandomListNode head, Dictionary<RandomListNode, RandomListNode> dict) {
14+
while (head != null) {
15+
RandomListNode node = new RandomListNode(head.label);
16+
dict.Add(head, node);
17+
head = head.next;
18+
}
19+
}
20+
private void CopyList(RandomListNode head, Dictionary<RandomListNode, RandomListNode> dict) {
21+
while (head != null) {
22+
RandomListNode temp = dict[head];
23+
if (head.next != null) {
24+
temp.next = dict[head.next];
25+
}
26+
if (head.random != null) {
27+
temp.random = dict[head.random];
28+
}
29+
head = head.next;
30+
}
31+
}
32+
33+
}
34+
/**
35+
* Definition for singly-linked list with a random pointer.
36+
* public class RandomListNode {
37+
* public int label;
38+
* public RandomListNode next, random;
39+
* public RandomListNode(int x) { this.label = x; }
40+
* };
41+
*/

0 commit comments

Comments
 (0)