01、(golang)FIFO循环队列

知识点学习
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;
   }
}

你可能感兴趣的:(数据结构与算法,go,队列,golang)