-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23. Merge k Sorted Lists.go
49 lines (45 loc) · 1.05 KB
/
23. Merge k Sorted Lists.go
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
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeList(l1 *ListNode, l2 *ListNode) *ListNode{
dummy := new(ListNode)
tail := dummy
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
tail.Next = l1
l1 = l1.Next
} else {
tail.Next = l2
l2 = l2.Next
}
tail = tail.Next
}
if l1 != nil {
tail.Next = l1
} else if l2 != nil {
tail.Next = l2
}
return dummy.Next
}
func mergeKLists(lists []*ListNode) *ListNode {
if lists == nil || len(lists) == 0 {
return nil
}
for len(lists) > 1 {
var mergedLists []*ListNode
for i := 0; i < len(lists); i += 2 {
l1 := lists[i]
var l2 *ListNode
if (i + 1) < len(lists) {
l2 = lists[i + 1]
}
mergedLists = append(mergedLists, mergeList(l1, l2))
}
lists = mergedLists
}
return lists[0]
}