循环队列
复盘:
isFull 的地方遗漏了取余操作 , rear 的边界处理没想到
画图的时候没走完整可能性 , 下次画的时候可以每走一步,根据图和伪代码执行一次所有函数
定义
data 存放数据的有限长度数组
head 指向队列头的第一个元素, 初始化0
tail 指向队列尾的最后一个元素 初始化 0
cap 容量 = len(data) -1
dataLen 数组长度
画图
入队
data[tail] = number
tail = tail++ % dataLen
return


出队
if this.isEmpty() throw Exception
res=data[head]
head=head+1 % dataLen
return res

tail 循环

队列满状态
if (tail+1)%dataLen==head

队列空状态
if head==tail


Accepted:
type MyCircularQueue struct {
data []int
head int
tail int
cap int
len int
}
/** Initialize your data structure here. Set the size of the queue to be k. */
func Constructor(k int) MyCircularQueue {
q := MyCircularQueue{data: make([]int, k+1), head: 0, tail: 0, cap: k, len: k+1}
return q
}
/** 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.data[this.tail] = value
this.tail=(this.tail+1) % this.len
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
}
//res:=this.data[head]
this.head=(this.head+1) % this.len
return true
}
/** Get the front item from the queue. */
func (this *MyCircularQueue) Front() int {
if this.IsEmpty() {
return -1
}
return this.data[this.head]
}
/** Get the last item from the queue. */
func (this *MyCircularQueue) Rear() int {
if this.IsEmpty() {
return -1
}
if this.tail==0 {
return this.data[this.len-1]
}
return this.data[(this.tail-1)%this.len]
}
/** Checks whether the circular queue is empty or not. */
func (this *MyCircularQueue) IsEmpty() bool {
if this.head==this.tail {
return true
}
return false
}
/** Checks whether the circular queue is full or not. */
func (this *MyCircularQueue) IsFull() bool {
if (this.tail+1)%this.len==this.head {
return true
}
return false
}
网友评论