Go实现数据结构--队列

使用golang语言的interface接口类型创建队列,队列可以操作各种数据类型,非常简洁方便

package main

import "fmt"

// 队列,先进先出(FIFO)
type Queue struct {
    Header   int            // 队头
    Tail     int            // 队尾,指向下一个元素
    Prt      *[]interface{} // 指向队列指针
    Capacity int            // 队列总容量
    Len      int            // 队列元素长度
}

// 初始化
func (q *Queue) QueueInital(capacity int) {
    // 创建队列,使用接口类型,所有数据类型都能用
    m := make([]interface{}, capacity)
    q.Capacity = capacity
    q.Len = 0
    q.Tail = 0
    q.Header = 0
    // 指针传递
    q.Prt = &m
}

// 插入一个值到队尾
func (q *Queue) QueueInsert(i interface{}) bool {
    // 判断队列是否为满
    if q.QueueIsFull() {
        fmt.Println("The queue is full")
        return false
    } else {
        // 将值插入队尾
        (*q.Prt)[q.Tail] = i
        q.Tail++
        q.Len++
        return true
    }
}

// 取出值,取队首
func (q *Queue) QueueTake() (interface{}, bool) {
    var em interface{}
    // 判空
    if q.QueueIsEmpty() {
        fmt.Println("The queue is empty")
        return nil, false
    } else {
        // 取走队首
        em = (*q.Prt)[q.Header]
        // 整体元素向前移一位
        for i := 0; i < q.Tail-1; i++ {
            (*q.Prt)[i] = (*q.Prt)[i+1]
        }
        q.Tail--
        q.Len--
        // 原空位补nil
        for i := q.Tail; i < q.Capacity; i++ {
            (*q.Prt)[i] = nil
        }
    }
    return em, true
}

// 判满
func (q *Queue) QueueIsFull() bool {
    if q.Tail >= q.Capacity {
        return true
    } else {
        return false
    }
}

// 判空
func (q *Queue) QueueIsEmpty() bool {
    if q.Len == 0 {
        return true
    } else {
        return false
    }

}

// 清空队列
func (q *Queue) QueueClear() {
    for i, _ := range *q.Prt {
        (*q.Prt)[i] = nil
    }
    q.Len = 0
    q.Tail = 0
}

func main() {
    // 定义一个队列
    var q Queue
    // 设置队列容量为4
    q.QueueInital(4)
    // 判空,true
    fmt.Println(q.QueueIsEmpty())
    // 定义一个Struct类型
    type s struct {
        name string
        age  int
    }
    student1 := s{name: "abc", age: 10}
    student2 := s{name: "efg", age: 10}
    // 插Struct类型
    q.QueueInsert(student1)
    q.QueueInsert(student2)
    // 插入int类型
    q.QueueInsert(100)
    // 插入string类型
    q.QueueInsert("hejk")
    // The queue is full
    q.QueueInsert("hejk2")
    // false
    fmt.Println(q.QueueIsEmpty())
    //  true
    fmt.Println(q.QueueIsFull())
    // [{abc 10} {efg 10} 100 hejk]
    fmt.Println(*q.Prt)
    // 取出队首
    em, _ := q.QueueTake()
    // {abc 10}
    fmt.Println(em)
    fmt.Println(*q.Prt)
    // 清空
    q.QueueClear()
    // [   ]
    fmt.Println(*q.Prt)
    // true
    fmt.Println(q.QueueIsEmpty())
}

你可能感兴趣的:(Go实现数据结构--队列)