我正在尝试使用链表在Java中实现双端队列。首先,我想实现addFirst()
方法。这是我遇到的问题-当我添加几个字符串(例如“一个”,“两个”和“三个”)时,它可以正确插入,但是在对双端队列进行迭代时,它仅给出最后一个添加的对象,并非所有对象。我有什么想念的吗?
public class Deque<Item> implements Iterable<Item> {
private Node first;
private Node last;
private int N;
public Iterator<Item> iterator() { return new DequeIterator(); }
private class Node {
private Item item;
private Node next;
}
public Deque() {
first = null;
last = null;
N = 0;
}
public boolean isEmpty() { return first == null || last == null; }
public int size() { return N; }
public void addFirst(Item item) {
if (null == item) { throw new NullPointerException("Can not add a null value"); }
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = null;
if (isEmpty()) {
last = first;
} else {
oldFirst.next = first;
}
N++;
}
private class DequeIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) { throw new NoSuchElementException(); }
Item item = current.item;
current = current.next;
return item;
}
}
public static void main(String args[]) {
Deque<String> deque = new Deque<String>();
deque.addFirst("one");
deque.addFirst("two");
deque.addFirst("three");
deque.addFirst("four");
for (String s : deque) {
System.out.println(s); // prints only "four"
}
}
}
最佳答案
将oldFirst.next = first
中的first.next = oldFirst
更改为addFirst()
,它应该可以工作。
现在,调用first.next
之后的addFirst()
没有指向任何内容,因为您将其设置为null
。这导致hasNext()
方法返回false,从而导致无效的迭代。