题目描述
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。
循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
你的实现应该支持如下操作:
MyCircularQueue(k): 构造器,设置队列长度为 k 。 Front: 从队首获取元素。如果队列为空,返回 -1 。 Rear: 获取队尾元素。如果队列为空,返回 -1 。 enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。 deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。 isEmpty(): 检查循环队列是否为空。 isFull(): 检查循环队列是否已满。
来源:力扣(LeetCode) 链接:leetcode.cn/problems/de… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
很基础的算法题,当时想着是用链表实现, 一直在纠结题目 “循环” 队列,犹豫要不要把 tail的next指向 head 后来发现没必要,因为是链表实现, 所以判断链表满并不需要用 (tail - head) mod n 这种方法 后来想想这么写确实浪费性能,每次出队都会导致内存空间浪费,也许会产生很多不必要的碎片,还是不如数组实现,尽管麻烦点
坑
1. todo 用数组写法实现一次
解法
- 链表解法
package leetcode
type NiNode struct {
val int
next *NiNode
front *NiNode
}
type MyCircularQueue struct {
length int
cap int
head *NiNode
tail *NiNode
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{cap: k}
}
func (q *MyCircularQueue) EnQueue(value int) bool {
if q.IsFull() {
return false
}
n := &NiNode{val: value}
if q.head == nil {
q.head = n
q.tail = n
} else {
q.tail.next = n
q.tail = n
}
q.length++
return true
}
func (q *MyCircularQueue) DeQueue() bool {
if q.IsEmpty() {
return false
}
q.head = q.head.next
q.length--
return true
}
func (q *MyCircularQueue) Front() int {
if q.IsEmpty() {
return -1
}
return q.head.val
}
func (q *MyCircularQueue) Rear() int {
if q.IsEmpty() {
return -1
}
return q.tail.val
}
func (q *MyCircularQueue) IsEmpty() bool {
return q.length == 0
}
func (q *MyCircularQueue) IsFull() bool {
return q.length == q.cap
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* obj := Constructor(k);
* param_1 := obj.EnQueue(value);
* param_2 := obj.DeQueue();
* param_3 := obj.Front();
* param_4 := obj.Rear();
* param_5 := obj.IsEmpty();
* param_6 := obj.IsFull();
*/
解法2
package leetcode
type MyCircularQueue struct {
front int
rear int
target []int
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{target: make([]int, k+1)}
}
func (q *MyCircularQueue) EnQueue(value int) bool {
if q.IsFull() {
return false
} else {
q.target[q.rear] = value
q.rear = (q.rear + 1) % len(q.target)
return true
}
}
func (q *MyCircularQueue) DeQueue() bool {
if q.IsEmpty() {
return false
} else {
q.front = (q.front + 1) % len(q.target)
return true
}
}
func (this *MyCircularQueue) Front() int {
if this.IsEmpty() {
return -1
}
return this.target[this.front]
}
func (this *MyCircularQueue) Rear() int {
if this.IsEmpty() {
return -1
}
return this.target[(this.rear-1+len(this.target))%len(this.target)]
}
func (this *MyCircularQueue) IsEmpty() bool {
return this.rear == this.front
}
func (this *MyCircularQueue) IsFull() bool {
return (this.rear+1)%len(this.target) == this.front
}