diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/README.md" index 46dda02934b66..87883e307c733 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/README.md" @@ -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.. 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 + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.swift" new file mode 100644 index 0000000000000..d6c00ecb4c6b9 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/Solution.swift" @@ -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.. 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 + } +} \ No newline at end of file