-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
50 lines (47 loc) · 1.24 KB
/
Program.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
using System;
using System.Collections.Generic;
namespace CopyListWithRandomPointer
{
public class Node
{
public int val;
public Node next;
public Node random;
public Node(int _val)
{
val = _val;
next = null;
random = null;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
static Node CopyRandomList(Node head)
{
var dict = new Dictionary<Node, Node>();
var newHead = CopyNode(head, dict);
var cur = head;
var newCur = newHead;
while (cur != null)
{
newCur.next = CopyNode(cur.next, dict);
newCur.random = CopyNode(cur.random, dict);
cur = cur.next;
newCur = newCur.next;
}
return newHead;
}
static Node CopyNode(Node node, Dictionary<Node, Node> dict)
{
if (node == null) return null;
if (dict.ContainsKey(node)) return dict[node];
var newNode = new Node(node.val);
dict[node] = newNode;
return newNode;
}
}
}