-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_k_sorted_lists.go
74 lines (62 loc) · 1.17 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"container/heap"
"fmt"
)
type ListNode struct {
Val int
Next *ListNode
}
type ListNodes []*ListNode
func (l ListNodes) Len() int {
return len(l)
}
func (l ListNodes) Less(i, j int) bool {
return l[i].Val <= l[j].Val
}
func (l ListNodes) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
func (l *ListNodes) Pop() interface{} {
n := len(*l)
x := (*l)[n-1]
*l = (*l)[:n-1]
return x
}
func (l *ListNodes) Push(x interface{}) {
*l = append(*l, x.(*ListNode))
}
var _ heap.Interface = (*ListNodes)(nil)
func mergeKLists(lists []*ListNode) *ListNode {
dummy := new(ListNode)
pre := dummy
hp := &ListNodes{}
for i := 0; i < len(lists); i++ {
if lists[i] != nil {
heap.Push(hp, lists[i])
}
}
for len(*hp) > 0 {
top := heap.Pop(hp).(*ListNode)
pre.Next = top
pre = pre.Next
if top.Next != nil {
heap.Push(hp, top.Next)
}
}
return dummy.Next
}
func printHP(hp ListNodes) {
fmt.Printf("\nhp: len: %d \n", len(hp))
for i := 0; i < len(hp); i++ {
fmt.Printf("node %d: %v", i, (hp)[i])
}
}
func printNode(node *ListNode) {
fmt.Printf("\nnodes: ")
for node != nil {
fmt.Printf(" %v ->", node.Val)
node = node.Next
}
fmt.Printf("\n")
}