检查优先队列是否为空的Go语言程序
优先队列是一种队列,其中元素与其优先级值一起存储。优先队列支持的函数包括:入队和出队,其中入队表示将元素及其优先级添加到队列中,出队表示从队列中删除元素及其优先级。在本文中,我们将编写一个Go语言程序来检查优先队列是否为空。
语法
func make ([] type, size, capacity)
Go语言中的`make`函数用于创建数组/映射,它接受要创建的变量类型、大小和容量作为参数。
func append(slice, element_1, element_2…, element_N) []T
`append`函数用于向数组切片中添加值。它接受多个参数。第一个参数是要向其添加值的数组,后跟要添加的值。然后,该函数返回包含所有值的最终数组切片。
func len(v Type) int
`len()`函数用于获取任何参数的长度。它接受一个参数作为要查找其长度的数据类型变量,并返回一个整数,表示该变量的长度。
算法
步骤1 - 创建一个Item结构体,其中包含三个字段:值为字符串类型,优先级为int类型,索引为int类型。
步骤2 - 然后,创建一个PriorityQueue类型作为`*Item`指针的切片,并为PriorityQueue类型创建Len、Less、Swap、Push和Pop方法。
步骤3 - 然后,为PriorityQueue类型实现IsEmpty方法,以检查优先队列的长度是否为零。
步骤4 - 在main函数中,使用`make`内置函数创建一个空的PriorityQueue并将其赋值为pq。然后,使用IsEmpty方法检查pq是否为空,并在控制台上打印输出。
步骤5 - 创建一个值为“chocolate”,优先级为2的项并将其推入pq。在此步骤中,创建另一个值为“milk-shake”,优先级为1的项并将其推入pq。
步骤6 - 检查pq是否为空,并在控制台上打印输出。然后,使用`heap.Pop`从pq中删除一个项。
步骤7 - 最后,检查pq是否为空,并打印输出。
示例1
在这个例子中,我们将编写一个Go语言程序,使用`container/heap`包的内部方法来检查优先队列是否为空。
package main
import (
"container/heap"
"fmt"
)
type Item struct {
value string
priority int
index int
}
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
return pq[i].priority < pq[j].priority
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
item.index = -1
*pq = old[0 : n-1]
return item
}
func (pq *PriorityQueue) IsEmpty() bool {
return len(*pq) == 0
}
func main() {
pq := make(PriorityQueue, 0)
heap.Init(&pq)
fmt.Println("Is priority queue empty?", pq.IsEmpty())
item1 := &Item{
value: "chocolate",
priority: 2,
}
heap.Push(&pq, item1)
fmt.Println("Is priority queue empty?", pq.IsEmpty())
item2 := &Item{
value: "milk shake",
priority: 1,
}
heap.Push(&pq, item2)
fmt.Println("Is priority queue empty?", pq.IsEmpty())
_ = heap.Pop(&pq)
fmt.Println("Is priority queue empty?", pq.IsEmpty())
_ = heap.Pop(&pq)
fmt.Println("Is priority queue empty?", pq.IsEmpty())
}
输出
Is priority queue empty? true Is priority queue empty? false Is priority queue empty? false Is priority queue empty? false Is priority queue empty? true
结论
在本文中,我们讨论了如何检查我们的语言中优先队列是否为空。我们已经执行了此操作的程序,该程序使用了`container/heap`包。空的优先队列看起来可能没用,但它是大型算法的构建块,提供了灵活性,并且可以以多种其他方式使用。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP