使用go语言创建一个简单的队列

package main

import "fmt"

/*
  add        增加一个元索                     如果队列已满,则抛出一个IIIegaISlabEepeplian异常
  remove   移除并返回队列头部的元素    如果队列为空,则抛出一个NoSuchElementException异常
  element  返回队列头部的元素             如果队列为空,则抛出一个NoSuchElementException异常
  offer       添加一个元素并返回true       如果队列已满,则返回false
  poll         移除并返问队列头部的元素    如果队列为空,则返回null
  peek       返回队列头部的元素             如果队列为空,则返回null
  put         添加一个元素                      如果队列满,则阻塞
  take        移除并返回队列头部的元素     如果队列为空,则阻塞
 */
type Queue struct {
    maxSize int
    array []interface{}
    front int
    rear int
}

//初始化队列
func NewQueue(size int) *Queue {
    if size < 1 {
        size = 10 //设置默认值为10
    }
    return &Queue{
        maxSize:size,
        array:make([]interface{}, size),
        front:-1,
        rear:-1,
    }
}
func main() {
    queue := NewQueue(3)
    queue.offer(1)
    queue.offer(2)
    queue.offer(3)
    b := queue.offer(4)
    fmt.Println(b)
    fmt.Println(queue)
    fmt.Println(queue.poll())
    fmt.Println(queue.poll())
    fmt.Println(queue.poll())
    fmt.Println(queue.poll())
    queue.offer(5)
    queue.offer(6)
    queue.offer(7)
    b2 := queue.offer(8)
    fmt.Println(b2)
    fmt.Println(queue)
    fmt.Println(queue.poll())
    fmt.Println(queue.poll())
    fmt.Println(queue.poll())
    fmt.Println(queue.poll())
}
//添加数据在队列
func (this *Queue) offer(val interface{}) bool {
    //先判断队列是否满
    if (this.rear - this.front) == this.maxSize {
        return false
    }
    this.rear++
    this.array[this.rear - this.front - 1] = val
    return true
}

//返回队列头部元素并移除
func (this *Queue) poll() interface{} {
    //判断队列是否为空
    if this.rear == this.front {
        return nil
    }
    this.front++
    var val  = this.array[this.front % this.maxSize]
    this.array[this.front % this.maxSize] = nil
    return val
}

转载于:https://www.cnblogs.com/hirampeng/p/11220448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值