Java 双链表上的迭代器
Java Iterator on Doubly-linked-list
您好,我是 Java 的新手,在为 双链表 构建嵌套迭代器 class 时遇到了这个问题。我不确定如何编写 public E next()
方法让它遍历 双链表 .
非常感谢任何帮助!
private class DoubleListIterator implements Iterator<E> {
// instance variable
private Node current=head;
private Node last;
private int index=0;
public boolean hasNext() {
return index < N;
}
public E next() {
if (!hasNext()) throw new NoSuchElementException();
}
public void remove() { throw new UnsupportedOperationException(); }
}// end class ListIterator
试试这个:
public boolean hasNext() {
return current != null;
}
public E next() {
if (!hasNext()) throw new NoSuchElementException();
E tmp = current.item;
current = current.next; // if next is null, hasNext will return false.
return tmp;
}
同时删除 last
和 index
,你不需要它们。
public E next() {
if (!hasNext()) throw new NoSuchElementException();
current = current.next;
return current;
}
你可能想看看 java.util.LinkedList :
List和Deque接口的双向链表实现。实现所有可选的列表操作,并允许所有元素(包括 null)。
所有操作的执行都符合双向链表的预期。索引到列表中的操作将从开头或结尾遍历列表,以更接近指定索引的为准。
LinkedList<String> linkedlist = new LinkedList<String>();
//add(String Element) is used for adding
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
/*Add First and Last Element*/
linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
//you can get the iterator by
ListIterator<String> it = linkedlist.listIterator();
您好,我是 Java 的新手,在为 双链表 构建嵌套迭代器 class 时遇到了这个问题。我不确定如何编写 public E next()
方法让它遍历 双链表 .
非常感谢任何帮助!
private class DoubleListIterator implements Iterator<E> {
// instance variable
private Node current=head;
private Node last;
private int index=0;
public boolean hasNext() {
return index < N;
}
public E next() {
if (!hasNext()) throw new NoSuchElementException();
}
public void remove() { throw new UnsupportedOperationException(); }
}// end class ListIterator
试试这个:
public boolean hasNext() {
return current != null;
}
public E next() {
if (!hasNext()) throw new NoSuchElementException();
E tmp = current.item;
current = current.next; // if next is null, hasNext will return false.
return tmp;
}
同时删除 last
和 index
,你不需要它们。
public E next() {
if (!hasNext()) throw new NoSuchElementException();
current = current.next;
return current;
}
你可能想看看 java.util.LinkedList :
List和Deque接口的双向链表实现。实现所有可选的列表操作,并允许所有元素(包括 null)。 所有操作的执行都符合双向链表的预期。索引到列表中的操作将从开头或结尾遍历列表,以更接近指定索引的为准。
LinkedList<String> linkedlist = new LinkedList<String>();
//add(String Element) is used for adding
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
/*Add First and Last Element*/
linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
//you can get the iterator by
ListIterator<String> it = linkedlist.listIterator();