-
Notifications
You must be signed in to change notification settings - Fork 0
/
priority_queue.go
59 lines (50 loc) · 1.64 KB
/
priority_queue.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
package main
import (
"container/heap"
"fmt"
)
type ConfServerNode struct {
Val int
Next *ConfServerNode
}
// 定义一个优先级队列
type PriorityConfServerQueue []*ConfServerNode
func (priorityConfServerQueue PriorityConfServerQueue) Len() int {
return len(priorityConfServerQueue)
}
// 小于(<)就是小顶堆, 大于(>)就是大顶堆
func (priorityConfServerQueue PriorityConfServerQueue) Less(i, j int) bool {
return priorityConfServerQueue[i].Val < priorityConfServerQueue[j].Val
}
func (priorityConfServerQueue PriorityConfServerQueue) Swap(i, j int) {
priorityConfServerQueue[i], priorityConfServerQueue[j] = priorityConfServerQueue[j], priorityConfServerQueue[i]
return
}
func (priorityConfServerQueue *PriorityConfServerQueue) Push(x interface{}) {
*priorityConfServerQueue = append(*priorityConfServerQueue, x.(*ConfServerNode))
}
func (priorityConfServerQueue *PriorityConfServerQueue) Pop() interface{} {
old := *priorityConfServerQueue
n := len(old)
x := old[n-1]
*priorityConfServerQueue = old[0 : n-1]
return x
}
func main() {
priorityConfServerQueue := &PriorityConfServerQueue{}
heap.Init(priorityConfServerQueue)
node1 := &ConfServerNode{Val: 4}
node2 := &ConfServerNode{Val: 3}
node3 := &ConfServerNode{Val: 2}
node4 := &ConfServerNode{Val: 6}
node5 := &ConfServerNode{Val: 1}
heap.Push(priorityConfServerQueue, node1)
heap.Push(priorityConfServerQueue, node2)
heap.Push(priorityConfServerQueue, node3)
heap.Push(priorityConfServerQueue, node4)
heap.Push(priorityConfServerQueue, node5)
for priorityConfServerQueue.Len() > 0 {
node := heap.Pop(priorityConfServerQueue)
fmt.Print(node.(*ConfServerNode).Val, " ")
}
}