golang实现队列

队列

概念:有序列表,可用数组或链表实现,先入先出

  1. 数组实现:需要环形队列,否则不能重复利用

数组实现环形队列实现(golang实现)


type MyCircularQueue struct {
	arr     []int
	maxsize int
	front   int
	rear    int
}


/*Initialize your data structure here. Set the size of the queue to be k. */
func Constructor(k int) MyCircularQueue {
	return MyCircularQueue{
		arr: make([]int, k),
		maxsize:k,
	}
}


/*Insert an element into the circular queue. Return true if the operation is successful. */
func (this *MyCircularQueue) EnQueue(value int) bool {
	if this.IsFull() {
		return false
	}
	this.arr[this.rear] = value
	this.rear = (this.rear + 1)%this.maxsize
	return true
}


/*Delete an element from the circular queue. Return true if the operation is successful. */
func (this *MyCircularQueue) DeQueue() bool {
	if this.IsEmpty() {
		return false
	}
	this.arr[this.front] = 0
	this.front = (this.front + this.maxsize + 1) % this.maxsize
	return true
}


/*Get the front item from the queue. */
func (this *MyCircularQueue) Front() int {
	return this.arr[this.front]
}


/*Get the last item from the queue. */
func (this *MyCircularQueue) Rear() int {
	return this.arr[(this.rear + this.maxsize)%this.maxsize]
}


/*Checks whether the circular queue is empty or not. */
func (this *MyCircularQueue) IsEmpty() bool {
	return this.rear== this.front
}


/*Checks whether the circular queue is full or not. */
func (this *MyCircularQueue) IsFull() bool {
	return (this.rear+this.maxsize-this.front)%this.maxsize == this.maxsize -1
}


func (this *MyCircularQueue) Show() {
	for i := this.front; i < this.front + (this.rear-this.front+this.maxsize)%this.maxsize; i++ {
		fmt.Println("index is %d, val is %d", (i)%this.maxsize, this.arr[i%this.maxsize])
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值