我正在尝试使用链表在java中实现Deque。首先,我想实现该方法addFirst()
.这是我遇到的问题 - 当我添加几个字符串时,例如"一","二"和"三",它插入正确,但是在迭代deque时,它只给出最后添加的对象,而不是所有对象。我缺少什么吗?
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"
}
}
}
在 addFirst()
中将oldFirst.next = first
更改为 first.next = oldFirst
,它应该可以工作。
现在first.next
addFirst()
通话后没有指向任何内容,因为您将其设置为 null
.这会导致 hasNext()
方法返回 false,从而导致无效迭代。
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private Deque.Node first;
private Deque.Node last;
private int N;
public Iterator<Item> iterator() {
return new Deque.DequeIterator();
}
private class Node {
private Item item;
private Deque.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");
}
if (first == null && last == null) {
first = new Node();
first.item = item;
first.next = null;
last = first;
} else {
Node node = new Node();
node.item = item;
node.next = first;
first = node;
}
N++;
}
private class DequeIterator implements Iterator<Item> {
private Deque.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 = (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"
}
}
}
输出:
four
three
two
one