-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo_138.cs
79 lines (67 loc) · 1.98 KB
/
No_138.cs
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
70
71
72
73
74
75
76
77
78
79
using System.Data.Common;
namespace LeetCode
{
public class No_138
{
public Node? CopyRandomList(Node? head)
{
if (head == null)
return null;
Dictionary<Node, Node> refer = new Dictionary<Node, Node>();
Node? copy = new Node(head.val);
Node? end = null;
Node? p = copy;
while (head != null)
{
if (head.next != null)
{
if (refer.ContainsKey(head.next))
p.next = refer[head.next];
else
{
p.next = new Node(head.next.val);
//refer.Add(head.next, p.next);
refer[head.next] = p.next;
}
}
else
p.next = end;
if (head.random != null && head.random != head)
{
if (!refer.ContainsKey(head.random))
{
p.random = new Node(head.random.val);
//refer.Add(head.random, p.random);
refer[head.random] = p.random;
}
else p.random = refer[head.random];
}
else
{
if (head.random == head)
p.random = p;
else p.random = end;
}
if (!refer.ContainsKey(head))
//refer.Add(head, p);
refer[head] = p;
head = head?.next;
p = p.next;
}
GC.Collect();
return copy;
}
}
public partial class Node
{
public int val;
public Node? next;
public Node? random;
public Node(int _val)
{
val = _val;
next = null;
random = null;
}
}
}