-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0138-CopyListWithRandomPointer.cs
74 lines (64 loc) · 1.86 KB
/
0138-CopyListWithRandomPointer.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
//-----------------------------------------------------------------------------
// Runtime: 92ms
// Memory Usage: 25 MB
// Link: https://leetcode.com/submissions/detail/379065640/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
/*
// Definition for a Node.
public class Node {
public int val;
public Node next;
public Node random;
public Node(){}
public Node(int _val,Node _next,Node _random) {
val = _val;
next = _next;
random = _random;
}
*/
public class _0138_CopyListWithRandomPointer
{
public Node CopyRandomList(Node head)
{
if (head == null) return null;
var map = new Dictionary<Node, Node>();
var curr = head;
while (curr != null)
{
var clone = CloneNode(curr, map);
clone.next = CloneNode(curr.next, map);
clone.random = CloneNode(curr.random, map);
curr = curr.next;
}
return map[head];
}
private Node CloneNode(Node node, IDictionary<Node, Node> map)
{
if (node == null) return null;
if (map.ContainsKey(node)) return map[node];
var clone = new Node(node.val);
map[node] = clone;
return clone;
}
public class Node
{
public int val;
public Node next;
public Node random;
public Node() { }
public Node(int _val)
{
val = _val;
}
public Node(int _val, Node _next, Node _random)
{
val = _val;
next = _next;
random = _random;
}
}
}
}