priority queue

优先队列,即不按进栈顺序,按优先级出栈,又分为最大优先级队列和最小优先级队列

golang可以使用heap堆操作来实现一个优先级队列

heap的堆结构如下:

type Interface interface {
    sort.Interface
    Push(x interface{}) 
    Pop() interface{}   
}

故只需要实现sort的三个方法,和push,pop方法,即可实现一个优先级队列


package main

import (
	"container/heap"
	"fmt"
)

type stu struct {
	name string
	age  int
}
type Stu []stu

func (t *Stu) Len() int {
	return len(*t)
}

func (t *Stu) Less(i, j int) bool {
	return (*t)[i].age < (*t)[j].age
}
func (t *Stu) Swap(i, j int) {
	(*t)[i], (*t)[j] = (*t)[j], (*t)[i]
}

func (t *Stu) Push(x interface{}) {
	*t = append(*t, x.(stu))
}
func (t *Stu) Pop() interface{} {
	n := len(*t)
	x := (*t)[n-1]
	*t = (*t)[:n-1]
	return x
}
func main() {
	student := &Stu{{"Amy", 21}, {"Dav", 15}, {"Spo", 22}, {"Reb", 11}}
	heap.Init(student)
	one := stu{"hund", 9}
	heap.Push(student, one)
	for student.Len() > 0 {
		fmt.Printf("%v\n", heap.Pop(student))
	}
}

上面是一个最小优先级队列。把less里面改改,就是一个最大优先级了,当然,不太符合编程规范,哈哈。