File tree 2 files changed +99
-0
lines changed
2 files changed +99
-0
lines changed Original file line number Diff line number Diff line change @@ -289,6 +289,58 @@ public class Solution {
289
289
}
290
290
```
291
291
292
+ #### Swift
293
+
294
+ ``` swift
295
+ /* public class Node: Hashable {
296
+ * public var val: Int
297
+ * public var next: Node?
298
+ * public var random: Node?
299
+
300
+ * public init(_ val: Int) {
301
+ * self.val = val
302
+ * self.next = nil
303
+ * self.random = nil
304
+ * }
305
+
306
+ * public static func == (lhs: Node, rhs: Node) -> Bool {
307
+ * return lhs === rhs
308
+ * }
309
+
310
+ * public func hash(into hasher: inout Hasher) {
311
+ * hasher.combine(ObjectIdentifier(self))
312
+ * }
313
+ * }
314
+ */
315
+
316
+ class Solution {
317
+ func copyRandomList (_ head : Node? ) -> Node? {
318
+ var d = [Node: Node]()
319
+ let dummy = Node (0 )
320
+ var tail: Node? = dummy
321
+ var cur = head
322
+
323
+ while cur != nil {
324
+ tail? .next = Node (cur! .val )
325
+ tail = tail? .next
326
+ d[cur! ] = tail
327
+ cur = cur? .next
328
+ }
329
+
330
+ tail = dummy.next
331
+ cur = head
332
+
333
+ while cur != nil {
334
+ tail? .random = d[cur! .random ?? Node (0 )]
335
+ tail = tail? .next
336
+ cur = cur? .next
337
+ }
338
+
339
+ return dummy.next
340
+ }
341
+ }
342
+ ```
343
+
292
344
<!-- tabs: end -->
293
345
294
346
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ /* public class Node: Hashable {
2
+ * public var val: Int
3
+ * public var next: Node?
4
+ * public var random: Node?
5
+
6
+ * public init(_ val: Int) {
7
+ * self.val = val
8
+ * self.next = nil
9
+ * self.random = nil
10
+ * }
11
+
12
+ * public static func == (lhs: Node, rhs: Node) -> Bool {
13
+ * return lhs === rhs
14
+ * }
15
+
16
+ * public func hash(into hasher: inout Hasher) {
17
+ * hasher.combine(ObjectIdentifier(self))
18
+ * }
19
+ * }
20
+ */
21
+
22
+ class Solution {
23
+ func copyRandomList( _ head: Node ? ) -> Node ? {
24
+ var d = [ Node: Node] ( )
25
+ let dummy = Node ( 0 )
26
+ var tail : Node ? = dummy
27
+ var cur = head
28
+
29
+ while cur != nil {
30
+ tail? . next = Node ( cur!. val)
31
+ tail = tail? . next
32
+ d [ cur!] = tail
33
+ cur = cur? . next
34
+ }
35
+
36
+ tail = dummy. next
37
+ cur = head
38
+
39
+ while cur != nil {
40
+ tail? . random = d [ cur!. random ?? Node ( 0 ) ]
41
+ tail = tail? . next
42
+ cur = cur? . next
43
+ }
44
+
45
+ return dummy. next
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments