package
main
import
(
"container/heap"
"fmt"
)
type
IntHeap []int
func
(h *IntHeap) Len() int {
return
len(*h);
}
func
(h *IntHeap) Less(i, j int) bool {
return
(*h)[i] < (*h)[j];
}
func
(h *IntHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i];
}
func
(h *IntHeap) Push(x
interface
{}) {
*h = append(*h, x.(int))
}
func
(h *IntHeap) Pop()
interface
{} {
old := *h;
n := len(old);
x := old[n-1];
*h = old[0: n-1];
return
x;
}
func
(h *IntHeap) PrintHeap() {
i := 0
levelCount := 1
for
i+1 <= h.Len() {
fmt.Println((*h)[i: i+levelCount])
i += levelCount
if
(i + levelCount*2) <= h.Len() {
levelCount *= 2
}
else
{
levelCount = h.Len() - i
}
}
}
func
main() {
a := IntHeap{6, 2, 3, 1, 5, 4};
heap.Init(&a);
a.PrintHeap();
fmt.Println(heap.Pop(&a));
a.PrintHeap();
fmt.Println(heap.Pop(&a));
a.PrintHeap();
heap.Push(&a, 0);
heap.Push(&a, 8);
a.PrintHeap();
}
请发表评论