欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(golang)FIFO循环队列

程序员文章站 2024-03-18 11:18:22
...

知识点学习

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;
   }
}