知識點學習
20200519 更新,EnQueue,DeQueue中使用if進行隊首尾連接,其實應該用:this.head % k
作爲指針,就實現了循環。
1、因爲是新學的語言,其中結構體MyCircularQueue內數據初始化感覺處理的不好看,使用循環賦值的方式,後面有機會再更新。
2、有個小坑,當隊列爲空時,隊列front,rear返回的都是是-1.
type MyCircularQueue struct {
head int
tail int
arr []int
}
// Initialize your data structure here. Set the size of the queue to be k.
func Constructor(k int) MyCircularQueue {
var CircularQueue MyCircularQueue;
CircularQueue.head = -1;
CircularQueue.tail = -1;
for a := 0; a < k; a++{
CircularQueue.arr = append(CircularQueue.arr,0);
}
return CircularQueue;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
func (this *MyCircularQueue) EnQueue(value int) bool {
if (this.IsEmpty()) {
this.tail,this.head = 0,0;
this.arr[this.tail] = value;
} else if (this.IsFull()) {
return false;
}else if(this.tail == len(this.arr) - 1){
this.tail = 0;
this.arr[this.tail] = value;
}else{
this.tail++;
this.arr[this.tail] = value;
}
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;
}else if(this.head==this.tail){
this.head = -1;
this.tail = -1;
}else if(this.head == len(this.arr) - 1){
this.head = 0;
}else{
this.head++;
}
return true;
}
/** Get the front item from the queue. */
func (this *MyCircularQueue) Front() int {
if (this.IsEmpty()){
return -1;
}else{
return this.arr[this.head]
}
}
/** Get the last item from the queue. */
func (this *MyCircularQueue) Rear() int {
if (this.IsEmpty()){
return -1;
}else{
return this.arr[this.tail]
}
}
/** Checks whether the circular queue is empty or not. */
func (this *MyCircularQueue) IsEmpty() bool {
if (this.head == -1 && this.tail == -1){
return true;
}else{
return false;
}
}
/** Checks whether the circular queue is full or not. */
func (this *MyCircularQueue) IsFull() bool {
if (this.head == 0 && this.tail == len(this.arr) - 1){
return true;
}else if (this.tail == this.head - 1){
return true;
}else{
return false;
}
}