簡體   English   中英

將隊列實現為列表有什么問題?

[英]What is wrong with the implementation of my queue as a list?

我開始創建隊列的變量headtail ,當然這是列表的元素,我通過編寫head = tail = null在構造函數中創建一個空列表。 enq ,我創建了一個名為help的列表的新元素,它應該保存我想要放在列表末尾的新元素(因為它是一個隊列)。 當然,隊列的tail始終是我們剛才放在列表末尾的元素。 然后我檢查head是否為空(或者因為列表本身是空的,或者因為我們刪除了它的第一個元素,它應該總是與head相同),並且,如果有必要,我也將head定義為help 然后help應該顯示到列表的新空元素。

問題如下:當我測試我的程序時,它在第一次刪除后停止並告訴我列表已經是空的。

我猜錯誤在於方法deq 我想通過編寫head = head.next來刪除第一個元素,但我們之前將head定義為help ,因此, head.nexthelp.next相同,與null相同,因此boolean -method返回列表是空的,這會停止程序。

我可能要改變help.next的“方向”,但我不知道怎么做。 怎么能讓整個事情發揮作用?

創建列表的元素:

public class Entry {
  Object content;
  Entry next;
}

清單的實施:

public class QueueList implements List {

  private Entry head;
  private Entry tail;

  public QueueList() {
    head = tail = null;
  }

  public boolean empty() {
    return head == null;
  }

  public void enq(Object x) {
    Entry help = new Entry();
    help.content = x;
    tail = help;

    if (head == null) {
      head = help;
    }

    help.next = null;
  }

  public Object front() {
    return head.content;
  }

  public void deq() {
    head = head.next;
  }
}
  public void enq(Object x) {
    Entry help = new Entry();
    help.content = x;
    **tail = help;**

    if (head == null) {
      head = help;
    }

    help.next = null;
  }

任何時候隊列中始終只有一個元素。

這可以使用下面的enq()方法解決

public void enq(Object x) {
        Entry help = new Entry(x);

        if (head == null) {

            head = help;

            tail = head;

        } else {
            if (head == tail) {

                head.next = help;
                tail = help;



            } else {

                this.tail.next = help;
                this.tail = help;
            }
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM