Skip to content

feat: add swift implementation to lcof2 problem: No.028 #3027

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

Merged
merged 1 commit into from
Jun 4, 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
48 changes: 48 additions & 0 deletions lcof2/剑指 Offer II 028. 展平多级双向链表/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,54 @@ public:
};
```

#### Swift

```swift
/* class Node {
* var val: Int
* var prev: Node?
* var next: Node?
* var child: Node?

* init(_ val: Int) {
* self.val = val
* self.prev = nil
* self.next = nil
* self.child = nil
* }
* }
*/

class Solution {
private var dummy = Node(0)
private var tail: Node?

func flatten(_ head: Node?) -> Node? {
guard let head = head else {
return nil
}
tail = dummy
preOrder(head)
dummy.next?.prev = nil
return dummy.next
}

private func preOrder(_ node: Node?) {
guard let node = node else {
return
}
let next = node.next
let child = node.child
tail?.next = node
node.prev = tail
tail = node
node.child = nil
preOrder(child)
preOrder(next)
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
43 changes: 43 additions & 0 deletions lcof2/剑指 Offer II 028. 展平多级双向链表/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/* class Node {
* var val: Int
* var prev: Node?
* var next: Node?
* var child: Node?

* init(_ val: Int) {
* self.val = val
* self.prev = nil
* self.next = nil
* self.child = nil
* }
* }
*/

class Solution {
private var dummy = Node(0)
private var tail: Node?

func flatten(_ head: Node?) -> Node? {
guard let head = head else {
return nil
}
tail = dummy
preOrder(head)
dummy.next?.prev = nil
return dummy.next
}

private func preOrder(_ node: Node?) {
guard let node = node else {
return
}
let next = node.next
let child = node.child
tail?.next = node
node.prev = tail
tail = node
node.child = nil
preOrder(child)
preOrder(next)
}
}
Loading