Golang实现数组模拟环形队列


本文摘自网络,作者,侵删。

package main

import (
    "errors"
    "fmt"
    "os"
)

type Queue struct {
    MaxSize int
    Array   []int
    Front   int
    Rear    int
}

func (this *Queue) AddQueue(val int) error {
    // 判断队列是否已满
    if this.Rear-this.Front >= this.MaxSize {
        return errors.New("queue full")
    }
    // 数组偏移下标
    this.Rear++
    this.Array[this.Rear%this.MaxSize] = val
    return nil
}

func (this *Queue) GetQueue() (int, error) {
    if this.Rear == this.Front {
        return -1, errors.New("queue empty")
    }
    this.Front++
    return this.Array[this.Front%this.MaxSize], nil
}

func (this *Queue) ShowQueue() {
    fmt.Print("queue:")
    for i := this.Front + 1; i <= this.Rear; i++ {
        fmt.Printf("\tarr[%d]=%d", i%this.MaxSize, this.Array[i%this.MaxSize])
    }
    fmt.Println()
}

func main() {
    queue := &Queue{MaxSize: 5, Front: -1, Rear: -1, Array: make([]int, 5)}
    var action string
    var val int
    for {
        fmt.Println("1.输入add 表示添加数据到队列\n2.输入get 表示从队列获取数据\n3.输入show 表示显示队列\n4.输入exit 退出程序")
        fmt.Scanln(&action)
        switch action {
        case "add":
            fmt.Println("输入要入队列数:")
            fmt.Scanln(&val)
            err := queue.AddQueue(val)
            if err == nil {
                fmt.Printf("\t加入队列成功\n")
            } else {
                fmt.Printf("\t%s\n", err.Error())
            }
        case "get":
            val, err := queue.GetQueue()
            if err == nil {
                fmt.Printf("\t从队列中取出了: %d\n", val)
            } else {
                fmt.Printf("\t%s\n", err.Error())
            }
        case "show":
            queue.ShowQueue()
        case "exit":
            os.Exit(0)
        }

    }
}


本文来自:简书

感谢作者:_H_8f4a

查看原文:Golang实现数组模拟环形队列

相关阅读 >>

Golang单向链表

Go - httpclient 常用操作

“python太慢了、Golang糟透了、monGodb是最好的”:那些关于软件工程的“宗教”辩论

Golang使用protobuf的方法详解

Golang实现生成不重复随机数

Golang 创建型设计模式 原型模式

Golang 协程(Goroutine) 运行过程 与 并发

Go开源说第四期:Go-zero解读与最佳实践(上)

聊聊dubbo-Go-proxy的timeoutfilter

Go那些事儿|defer必掌握知识

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...