題目
設計你的循環隊列實現。 循環隊列是一種線性數據結構,其操作表現基於 FIFO(先進先出)原則並且隊尾被連接在隊首之後以形成一個循環。它也被稱爲“環形緩衝器”。
循環隊列的一個好處是我們可以利用這個隊列之前用過的空間。在一個普通隊列裏,一旦一個隊列滿了,我們就不能插入下一個元素,即使在隊列前面仍有空間。但是使用循環隊列,我們能使用這些空間去存儲新的值。
你的實現應該支持如下操作:
MyCircularQueue(k): 構造器,設置隊列長度爲 k 。
Front: 從隊首獲取元素。如果隊列爲空,返回 -1 。
Rear: 獲取隊尾元素。如果隊列爲空,返回 -1 。
enQueue(value): 向循環隊列插入一個元素。如果成功插入則返回真。
deQueue(): 從循環隊列中刪除一個元素。如果成功刪除則返回真。
isEmpty(): 檢查循環隊列是否爲空。
isFull(): 檢查循環隊列是否已滿。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/design-circular-queue
分析
循環隊列的要點在於隊列的head和tail的計算,每次enqueue,head要加1,並且要模上整個queue的長度Size,這樣長度就不會溢出,然後長度加1。每次dequeue,則count減去1,tail的index就是 (head+count - 1) % Size。是不是full,就看count == Size,是不是空,則count == 0。
解法
type MyCircularQueue struct {
Size int
Count int
Head int
Queue []int
}
/** Initialize your data structure here. Set the size of the queue to be k. */
func Constructor(k int) MyCircularQueue {
m := MyCircularQueue{
Size: k,
Head: 0,
Count: 0,
}
m.Queue = make([]int, k)
return m
}
/** 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.Queue[(this.Head + this.Count)%this.Size] = value
this.Count++
//fmt.Printf("enqueue: head: %d, count: %d, %v\n", this.Head, this.Count, this.Queue)
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.Head = (this.Head + 1)%this.Size
this.Count--
//fmt.Printf("dequeue: head: %d, count: %d, %v\n", this.Head, this.Count, this.Queue)
return true
}
/** Get the front item from the queue. */
func (this *MyCircularQueue) Front() int {
if this.IsEmpty() {
return -1
}
return this.Queue[this.Head]
}
/** Get the last item from the queue. */
func (this *MyCircularQueue) Rear() int {
if this.IsEmpty() {
return -1
}
return this.Queue[(this.Head+this.Count-1)%this.Size]
}
/** Checks whether the circular queue is empty or not. */
func (this *MyCircularQueue) IsEmpty() bool {
return this.Count == 0
}
/** Checks whether the circular queue is full or not. */
func (this *MyCircularQueue) IsFull() bool {
return this.Count == this.Size
}
/**
* 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();''
*/