重点介绍
在标准库 container
中,含有三种数据类型,分别是heap,list,ring; Go语言提供heap容器,但是不提供相关操作,故需要我们进行相关函数的重写; 导包
package main
import (
"container/heap"
"fmt"
)
type Interface interface {
sort. Interface
Push ( x interface { } )
Pop ( ) interface { }
}
type Interface interface {
Len ( ) int
Less ( i, j int ) bool
Swap ( i, j int )
}
故要用标准库的heap,需要实现下列五个接口函数,如下
{
Len ( ) int
Less ( i, j int ) bool
Swap ( i, j int )
Push ( x interface { } )
Pop ( ) interface { }
}
{
h := & IntHeap{ }
func Init ( h Interface)
func Push ( h Interface, x interface { } )
func Pop ( h Interface) interface { }
func Remove ( h Interface, i int ) interface { }
func Fix ( h Interface, i int )
}
实践
package main
import (
"fmt"
"container/heap"
)
func main ( ) {
h := & IntHeap{ 2 , 1 , 5 , 6 , 4 , 3 , 7 , 9 , 8 , 0 }
heap. Init ( h)
fmt. Println ( * h)
fmt. Println ( heap. Pop ( h) )
heap. Push ( h, 6 )
fmt. Println ( * h)
for len ( * h) > 0 {
fmt. Printf ( "%d " , heap. Pop ( h) )
}
}
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
}