我正在嘗試通過實現雙向鏈表格式來創建一個Deque類(可以添加到並在兩端引用的Stack/Queue)。Iterable Deque NullPointerException
import java.util.Iterator;
公共類的Deque實現了Iterable {
Node first;
Node last;
int size;
public Deque()
{
first = null;
last = null;
size = 2;
first.next = last;
last.prev = first;
}
private class Node
{
Node next;
Node prev;
Item item;
}
private class ListIterator implements Iterator<Item>
{
private Node current = first;
public boolean hasNext()
{
return current.next != null;
}
public Item next()
{
Item item = current.item;
current = current.next;
return item;
}
public void remove()
{
/* not supported */
}
}
public boolean isEmpty()
{
if(first == null&&last == null)
return true;
return false;
}
public int size()
{
return size;
}
public void addFirst(Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
oldfirst.prev = first;
size++;
}
public void addLast(Item item)
{
Node oldlast = last;
last = new Node();
last.item = item;
last.prev = oldlast;
oldlast.next = last;
size++;
}
public Item removeFirst()
{
Item item = first.item;
first = first.next;
size--;
return item;
}
public Item removeLast()
{
Item item = last.item;
last = last.next;
size--;
return item;
}
@Override
public Iterator<Item> iterator()
{
return (new ListIterator());
}
public static void main(String[] args)
{
Deque<Integer> deque = new Deque<Integer>();
for(int i=0; i<5; i++)
{
deque.addFirst(i);
deque.addLast(9-i);
}
for(Integer i : deque)
{
StdOut.println(i);
}
}
}
當我運行代碼,我得到一個NullPointerException異常時,它試圖做first.next =最後;我可以理解爲什麼,但我不確定如何修復它,而不會破壞列表。任何解決方案可能沒有必要使用雙向鏈接格式(即完全刪除prev引用節點)?
感謝您的幫助。是的,這是一個任務嚴格確定我不能使用任何給定的庫之外的任何庫。 – 2015-02-06 04:31:20