[英]What is wrong with the implementation of my queue as a list?
我開始創建隊列的變量head
和tail
,當然這是列表的元素,我通過編寫head = tail = null
在構造函數中創建一個空列表。 在enq
,我創建了一個名為help
的列表的新元素,它應該保存我想要放在列表末尾的新元素(因為它是一個隊列)。 當然,隊列的tail
始終是我們剛才放在列表末尾的元素。 然后我檢查head
是否為空(或者因為列表本身是空的,或者因為我們刪除了它的第一個元素,它應該總是與head
相同),並且,如果有必要,我也將head
定義為help
。 然后help
應該顯示到列表的新空元素。
問題如下:當我測試我的程序時,它在第一次刪除后停止並告訴我列表已經是空的。
我猜錯誤在於方法deq
。 我想通過編寫head = head.next
來刪除第一個元素,但我們之前將head
定義為help
,因此, head.next
與help.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.