forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
31 lines (27 loc) · 803 Bytes
/
Solution.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
using System;
using System.Collections.Generic;
public class Solution {
public Node CopyRandomList(Node head) {
if (head == null) {
return null;
}
var map = new Dictionary<Node, Node>();
var current = head;
while (current != null) {
var newCurrent = new Node(current.val);
map.Add(current, newCurrent);
current = current.next;
}
foreach (var entry in map) {
var oldNode = entry.Key;
var newNode = entry.Value;
if (oldNode.next != null) {
newNode.next = map[oldNode.next];
}
if (oldNode.random != null) {
newNode.random = map[oldNode.random];
}
}
return map[head];
}
}