[英]Why does my doubly linked list iterator print null?
我寫了一種方法,可以在雙向鏈表的前面添加一個項目。 每次調用該函數時,它都應添加通過它傳遞的項。 該功能按預期工作,除了當我遍歷雙向鏈接列表並打印每個項目時,它總是在末尾打印兩次null
。 我的代碼如下。
public Deque() {
first = new Node();
last = new Node();
first.next = last;
last.prev = first;
}
public void addFirst(E item) {
if (item.equals(null)) {
throw new NullPointerException();
} else {
if (first.equals(null) && last.equals(null)) {
first = new Node();
first.next.item = item;
first.next.next = null;
last = first;
} else {
Node node = new Node();
node.item = item;
node.next = first;
first = node;
}
}
N++;
}
public static void main(String[] args) {
Deque<Integer> lst = new Deque<Integer>(); // empty list
lst.addFirst(1);
lst.addFirst(5);
lst.addFirst(7);
lst.addFirst(9);
Iterator<Integer> it = lst.iterator(); // tests iterator method
while (it.hasNext()) {
Integer val = it.next();
System.out.println(val);
}
}
該代碼顯示: 9, 5, 7, 1, null, null
。 我無法弄清楚正在打印兩個額外的空值。 誰能告訴我如何解決我的代碼,使代碼最后不兩次輸出null
?
您正在創建兩個名為first
和last
節點,作為Deque
類的構造函數的一部分。
public Deque() {
first = new Node();
last = new Node();
first.next = last;
last.prev = first;
}
因此,您的物品會被添加到它們的前面。 當您打印出來時,它會打印您添加的內容,然后打印第一和最后一個,並且由於它們沒有設置項目,因此它會打印null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.