Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add swift implementation to lcof problem: No.35 #2905

Merged
merged 1 commit into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions lcof/面试题35. 复杂链表的复制/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,58 @@ public class Solution {
}
```

#### Swift

```swift
/* public class Node: Hashable {
* public var val: Int
* public var next: Node?
* public var random: Node?

* public init(_ val: Int) {
* self.val = val
* self.next = nil
* self.random = nil
* }

* public static func == (lhs: Node, rhs: Node) -> Bool {
* return lhs === rhs
* }

* public func hash(into hasher: inout Hasher) {
* hasher.combine(ObjectIdentifier(self))
* }
* }
*/

class Solution {
func copyRandomList(_ head: Node?) -> Node? {
var d = [Node: Node]()
let dummy = Node(0)
var tail: Node? = dummy
var cur = head

while cur != nil {
tail?.next = Node(cur!.val)
tail = tail?.next
d[cur!] = tail
cur = cur?.next
}

tail = dummy.next
cur = head

while cur != nil {
tail?.random = d[cur!.random ?? Node(0)]
tail = tail?.next
cur = cur?.next
}

return dummy.next
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
47 changes: 47 additions & 0 deletions lcof/面试题35. 复杂链表的复制/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/* public class Node: Hashable {
* public var val: Int
* public var next: Node?
* public var random: Node?

* public init(_ val: Int) {
* self.val = val
* self.next = nil
* self.random = nil
* }

* public static func == (lhs: Node, rhs: Node) -> Bool {
* return lhs === rhs
* }

* public func hash(into hasher: inout Hasher) {
* hasher.combine(ObjectIdentifier(self))
* }
* }
*/

class Solution {
func copyRandomList(_ head: Node?) -> Node? {
var d = [Node: Node]()
let dummy = Node(0)
var tail: Node? = dummy
var cur = head

while cur != nil {
tail?.next = Node(cur!.val)
tail = tail?.next
d[cur!] = tail
cur = cur?.next
}

tail = dummy.next
cur = head

while cur != nil {
tail?.random = d[cur!.random ?? Node(0)]
tail = tail?.next
cur = cur?.next
}

return dummy.next
}
}
Loading