-
LinkedList Iterator
For an assignment, I had to create my own LinkedList class -- called BasicLinkedList -- that has many methods similar to LinkedList. I have to create a BasicListIterator that can iterate through the list, which contains the next(), previous(), hasNext(), and hasPrevious() methods. I'm having trouble with this, and keep getting NullPointerExceptions whenever I try to test it. Please let me know what I'm doing wrong!!
Code:
private class Node
{
public E data;
public Node next;
public Node prev;
}
private Node head;
private class MyListIterator implements BasicListIterator<E>
{
private Node position = head;
public E next()
{
if(!(hasNext()))
{
throw new NoSuchElementException();
}
else
{
E data = position.data;
position = position.next;
return data;
}
}
public E previous()
{
if(!(hasPrevious()))
{
throw new NoSuchElementException();
}
else
{
System.out.println(position);
E data = position.prev.data;
position = position.prev;
return data;
}
}
public boolean hasNext()
{
if(position == null)
{
return false;
}
else
{
return true;
}
}
public boolean hasPrevious()
{
if(position == head)
{
return false;
}
else
{
return true;
}
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
-
Re: LinkedList Iterator
We don't read minds. Post your errors and indicate on which lines they occur.
-
Re: LinkedList Iterator
Sorry. Here are my tests. When I call iter.previous(), I get this error:
Exception in thread "main" java.lang.NullPointerException
at BasicLinkedList$MyListIterator.previous(BasicLinke dList.java:38)
Code:
BasicLinkedList<Integer> list = new BasicLinkedList<Integer>();
int[] ints = new int[] {99, 88, 77, 66, 55};
list.add(ints[0]);
BasicListIterator<Integer> iter = list.basicListIterator();
iter.next() == ints[0];
iter.previous() == ints[0];
-
Re: LinkedList Iterator
Code:
E data = position.prev.data;
Is that line 38?
When position is head then prev is null. So prev.data will throw a NPE.
-
Re: LinkedList Iterator
I changed it to just "position.data" but am still getting the same error...
-
Re: LinkedList Iterator
Think about it!
When you are at the head does it have a previous?
-
Re: LinkedList Iterator
No -- but we aren't at head. After calling iter.next(), we're at the next node; so prev would be the node we just went over.
-
Re: LinkedList Iterator
I see you have a print statement. Change it to print previous.data to see exactly which node is throwing the NPE. Then trace back as to what and why it is null.
-
Re: LinkedList Iterator
Tried that... Still can't figure it out. :(