Skip to content

Commit 01ad679

Browse files
authored
feat: add swift implementation to lcof problem: No.35 (#2905)
1 parent 41bfdfa commit 01ad679

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed

lcof/面试题35. 复杂链表的复制/README.md

+52
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,58 @@ public class Solution {
289289
}
290290
```
291291

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+
292344
<!-- tabs:end -->
293345

294346
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
}

0 commit comments

Comments
 (0)