循環(huán)隊(duì)列

要點(diǎn)

那么,循環(huán)隊(duì)列為什么用空一個(gè)元素的位置呢???

這個(gè)是根據(jù)需要來(lái)用的
循環(huán)隊(duì)列中,由于入隊(duì)時(shí)尾指du針向前追趕頭指針;zhi出隊(duì)時(shí)頭指針向前追趕尾指針,造成dao隊(duì)空和隊(duì)滿時(shí)頭尾指針均相等。因此,無(wú)法通過(guò)條件front==rear來(lái)判別隊(duì)列是"空"還是"滿"。
解決這個(gè)問(wèn)題的方法至少有三種:
①另設(shè)一布爾變量以區(qū)別隊(duì)列的空和滿;
②少用一個(gè)元素的空間。約定入隊(duì)前,測(cè)試尾指針在循環(huán)意義下加1后是否等于頭指針,若相等則認(rèn)為隊(duì)滿(注意:rear所指的單元始終為空);
③使用一個(gè)計(jì)數(shù)器記錄隊(duì)列中元素的總數(shù)(即隊(duì)列長(zhǎng)度)

因?yàn)椴扇×说诙N方法,所以要始終大1。

使用【頭尾指向一個(gè)位置】的條件來(lái)判斷空。使用【尾指針在頭指針前一個(gè)】的條件判斷滿

尾指針始終指向的是一個(gè)空位置,即下一個(gè)要填入的位置

頭指針在隊(duì)列為空時(shí)為第一個(gè)元素的位置,隊(duì)列不為空時(shí)為第一個(gè)元素的位置。實(shí)際上除了判斷滿和判斷空的方法外,對(duì)頭元素和頭指針的操作都經(jīng)過(guò)了空判斷過(guò)濾。所以允許空和非空時(shí)含義不一致。

代碼

public class CircularQueue {

  public static void main(String[] args) {

    Queue queue = new Queue(3);
    char key = ' ';
    Scanner scanner = new Scanner(System.in);
    boolean loop = true;
    while (loop) {
      System.out.println("s: show");
      System.out.println("e: exit");
      System.out.println("a: add");
      System.out.println("p: pop");
      key = scanner.next().charAt(0);
      switch (key) {
        case 's':
          queue.showQueue();
          break;
        case 'a':
          int value = scanner.nextInt();
          queue.addQueue(value);
          break;
        case 'p':
          queue.popQueue();
          break;
        case 'e':
          scanner.close();
          loop = false;
          break;
      }
    }
  }

}


class Queue {

  int maxSize;
  int front = 0;
  int rear = 0;
  int[] arr;

  public Queue(int maxSize) {
    this.maxSize = maxSize + 1;
    arr = new int[this.maxSize];
  }

  public boolean isFull() {
    if ((rear +1)%maxSize == front) {
      System.out.println("已滿");
      return true;
    }
    return false;
  }

  public boolean isEmpty() {
    if(front == rear){
      System.out.println("為空");
      return true;
    }
    return false;
  }

  public void addQueue(int data) {
    if (this.isFull()) {
      return;
    }
    System.out.println("輸入");
    this.arr[rear%maxSize] = data;
    rear++;
  }
  
  public void popQueue() {
    if (!isEmpty()) {
      int value = this.arr[front % maxSize];
      front++;
      System.out.println(value);
    }
  }

  public void showQueue() {
    if (!isEmpty()) {
      for (int i = front % maxSize; i < (rear-front)%maxSize + front % maxSize; i++) {
        System.out.printf("a[%d]=%d\n", i%maxSize, arr[i%maxSize]);
      }
    }
  }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容