Stack implementation code
For empty interfaces, remember that you need to use assertions and type conversions to get data
package main
import (
"fmt"
"reflect"
)
type Stack []interface{
}
func (p *Stack) Push(num interface{
}) {
*p = append(*p, num)
}
func (p Stack) Size() (size int) {
size = len(p)
return size
}
func (p *Stack) Pop() {
*p = (*p)[:len(*p)-1]
return
}
func (p Stack) Top() (res interface{
}) {
res = p[len(p)-1]
return
}
func (p Stack) Empty() bool {
return len(p) == 0
}
func main() {
var S = Stack{
}
S.Push(1)
S.Push(2)
S.Push("zpc")
var num = S.Top().(string) // 需要通过断言和数据类型转化才可以拿到数据
fmt.Println(S)
S.Pop()
fmt.Println(S)
fmt.Println(reflect.TypeOf(num))
fmt.Println(reflect.TypeOf(S.Top()))
}
implementation of the heap
package main
import (
"container/heap"
"fmt"
)
type Node struct {
data string // 数据
priority int // 优先级
}
type PriorityQueue []Node
func (p PriorityQueue) Len() (length int) {
length = len(p)
return
}
func (p PriorityQueue) Less(i, j int) bool {
return p[i].priority > p[j].priority // 控制大小根堆
}
func (p PriorityQueue) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p *PriorityQueue) Push(x interface{
}) {
value, ok := x.(Node)
if !ok {
fmt.Println("断言失败")
return
}
*p = append(*p, value)
}
func (p *PriorityQueue) Pop() (x interface{
}) {
x = (*p)[len(*p)-1]
*p = (*p)[:len(*p)-1]
return
}
func main() {
pq := make(PriorityQueue, 0, 10)
heap.Init(&pq)
fmt.Println()
heap.Push(&pq, Node{
"zpc", 1})
heap.Push(&pq, Node{
"zpc", 2})
heap.Push(&pq, Node{
"zpc", 3})
heap.Push(&pq, Node{
"zpc", 5})
heap.Push(&pq, Node{
"zpc", 4})
fmt.Println(pq)
fmt.Println(heap.Pop(&pq).(Node)) // 需要使用断言
fmt.Println(heap.Pop(&pq).(Node))
fmt.Println(heap.Pop(&pq).(Node))
fmt.Println(heap.Pop(&pq).(Node))
}
Implementation of the queue
package main
import "fmt"
type Queue []interface{
}
func (p *Queue) Push(num interface{
}) {
*p = append(*p, num)
}
func (p *Queue) Pop() {
*p = (*p)[1:len(*p)]
}
func (p Queue) Front() (num interface{
}) {
if len(p) <= 0 {
return
}
num = p[0]
return
}
func (p Queue) Size() (size int) {
size = len(p)
return
}
func (p Queue) Empty() bool {
return len(p) == 0
}
func main() {
queue := make(Queue, 0, 10)
fmt.Println(queue.Empty())
queue.Push(1)
queue.Push(2)
queue.Push(3)
fmt.Println(queue.Empty(), queue.Size(), queue.Front())
queue.Pop()
fmt.Println(queue)
}