Skip to content

Commit 065d74e

Browse files
committed
Adding 138. Copy List with Random Pointer in Swift
1 parent 825a25b commit 065d74e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Diff for: swift/138-Copy-List-with-Random-Pointer.swift

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
}

0 commit comments

Comments
 (0)