简体   繁体   中英

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 . I wasn't sure how to write a public E next() method to have it iterate through a Doubly-Linked-List .

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.

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

you may want to take a look at java.util.LinkedList :

From Documentation :

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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