Skip to content

feat: add swift implementation to lcof2 problem: No.078 #3457

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
Aug 30, 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 078. 合并排序链表/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,54 @@ def merge_two_lists(l1, l2)
end
```

#### Swift

```swift
/** class ListNode {
* var val: Int
* var next: ListNode?
* init() { self.val = 0; self.next = nil }
* init(_ val: Int) { self.val = val; self.next = nil }
* init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next }
* }
*/

class Solution {
func mergeKLists(_ lists: [ListNode?]) -> ListNode? {
let n = lists.count
if n == 0 {
return nil
}

var mergedList: ListNode? = lists[0]
for i in 1..<n {
mergedList = mergeLists(mergedList, lists[i])
}
return mergedList
}

private func mergeLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let dummy = ListNode()
var cur = dummy
var l1 = l1
var l2 = l2

while let node1 = l1, let node2 = l2 {
if node1.val <= node2.val {
cur.next = node1
l1 = node1.next
} else {
cur.next = node2
l2 = node2.next
}
cur = cur.next!
}
cur.next = l1 ?? l2
return dummy.next
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
43 changes: 43 additions & 0 deletions lcof2/剑指 Offer II 078. 合并排序链表/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/** class ListNode {
* var val: Int
* var next: ListNode?
* init() { self.val = 0; self.next = nil }
* init(_ val: Int) { self.val = val; self.next = nil }
* init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next }
* }
*/

class Solution {
func mergeKLists(_ lists: [ListNode?]) -> ListNode? {
let n = lists.count
if n == 0 {
return nil
}

var mergedList: ListNode? = lists[0]
for i in 1..<n {
mergedList = mergeLists(mergedList, lists[i])
}
return mergedList
}

private func mergeLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let dummy = ListNode()
var cur = dummy
var l1 = l1
var l2 = l2

while let node1 = l1, let node2 = l2 {
if node1.val <= node2.val {
cur.next = node1
l1 = node1.next
} else {
cur.next = node2
l2 = node2.next
}
cur = cur.next!
}
cur.next = l1 ?? l2
return dummy.next
}
}
Loading