go 关于栈、队列、优先队列的实现

栈的实现代码

空接口记得需要使用断言和类型转化拿到数据

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()))

}

堆的实现

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))
}

队列的实现

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)
}

猜你喜欢

转载自blog.csdn.net/qq_44741914/article/details/132307502