File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a Node.
3+ * public class Node {
4+ * public var val: Int
5+ * public var next: Node?
6+ * public var random: Node?
7+ * public init(_ val: Int) {
8+ * self.val = val
9+ * self.next = nil
10+ * self.random = nil
11+ * }
12+ * }
13+ */
14+
15+ class Solution {
16+ // Cache of mapping from old to new nodes
17+ private var mapping : [ Node ? : Node ? ] = [ : ]
18+
19+ func copyRandomList( _ head: Node ? ) -> Node ? {
20+ // Base case: Nil node
21+ guard let node = head else { return nil }
22+
23+ // Mapping exists
24+ guard mapping [ node] == nil else { return mapping [ node] ! }
25+
26+ // Create new node
27+ let newNode = Node ( node. val)
28+
29+ // Add to cache (i.e. 'visit' this node)
30+ mapping [ node] = newNode
31+
32+ // Recursive calls (preorder -> children calls)
33+ newNode. next = copyRandomList ( node. next)
34+ newNode. random = copyRandomList ( node. random)
35+
36+ return newNode
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments