-
Notifications
You must be signed in to change notification settings - Fork 0
/
0023.Merge k Sorted Lists.swift
52 lines (42 loc) · 1.15 KB
/
0023.Merge k Sorted Lists.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func mergeKLists(_ lists: [ListNode?]) -> ListNode? {
if lists.isEmpty {
return nil
}
var arr = [Int]()
for list in lists {
arr += toArray(list)
}
arr.sort()
return toList(arr)
}
private func toArray(_ node: ListNode?) -> [Int] {
var result = [Int]()
var pointer = node
while pointer != nil {
result.append(pointer!.val)
pointer = pointer!.next
}
return result
}
private func toList(_ arr: [Int]) -> ListNode? {
var head = ListNode()
var pointer = head
for el in arr {
var node = ListNode(el)
pointer.next = node
pointer = pointer.next!
}
return head.next
}
}