简体   繁体   English

双链表上的Java迭代器

[英]Java Iterator on Doubly-linked-list

Hi I'm very new to Java and have this problem with building a nested Iterator class for a Doubly Linked List . 嗨,我是Java的新手,为双链表构建嵌套的Iterator类时遇到了这个问题。 I wasn't sure how to write a public E next() method to have it iterate through a Doubly-Linked-List . 我不确定如何编写一个public E next()方法来使其遍历双链表

Any help is greatly appreciated! 任何帮助是极大的赞赏!

  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

Try this: 尝试这个:

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;
}

Also drop last and index , you dont need them. 还删除lastindex ,您不需要它们。

 public E next() {
        if (!hasNext()) throw new NoSuchElementException();
             current = current.next;
    return current;
    }

you may want to take a look at java.util.LinkedList : 您可能想看看java.util.LinkedList:

From Documentation : 从文档

Doubly-linked list implementation of the List and Deque interfaces. List和Deque接口的双链接列表实现。 Implements all optional list operations, and permits all elements (including null). 实现所有可选的列表操作,并允许所有元素(包括null)。 All of the operations perform as could be expected for a doubly-linked list. 所有操作均按双向链表的预期执行。 Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index. 索引到列表中的操作将从开头或结尾遍历列表,以更接近指定索引的位置为准。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM