class Node
{
public Object data;
public Node next;
}
public class LinkedList
{
private Node first;
...
}

public void addFirst(Object element)
{
Node newNode = new Node();
newNode.data = element;
newNode.next = first;
first = newNode;
}
public class LinkedList
{
. . .
public Object removeFirst()
{
if (first == null) { throw new NoSuchElementException(); }
Object element = first.data;
first = first.next;
return element;
}
. . .
}
next, hasNext, remove,
add, setremove, setnext
class LinkedListIterator implements ListIterator
{
private Node position;
private Node previous;
private boolean isAfterNext;
...
}
previous is needed for removalpublic Object next()
{
if (!hasNext()) { throw new NoSuchElementException(); }
previous = position; // Remember for remove
isAfterNext = true;
if (position == null)
{
position = first;
}
else
{
position = position.next;
}
return position.data;
}

hasNextpublic boolean hasNext()
{
if (position == null)
{
return first != null;
}
else
{
return position.next != null;
}
}
removepublic void remove()
{
if (!isAfterNext) { throw new IllegalStateException(); }
if (position == first)
{
removeFirst();
}
else
{
previous.next = position.next;
}
position = previous;
isAfterNext = false;
}
Suppose we removed the lines
if (!isAfterNext) { throw new IllegalStateException(); }
and
isAfterNext = false;
from the remove method. What would happen if one called remove
twice in a row?
addpublic void add(Object element)
{
if (position == null)
{
addFirst(element);
position = first;
}
else
{
Node newNode = new Node();
newNode.data = element;
newNode.next = position.next;
position.next = newNode;
position = newNode;
}
isAfterNext = false;
}
Actually, the table from the last slide isn't true for the implementation that we just studied. Which of them is false?
Ok, so let's add a tail reference.
public class LinkedList
{
private Node first;
private Node last;
...
}
Now we need to update it in all methods that mutate the list. Here is ListIterator.remove:
public void remove()
{
if (!isAfterNext) { throw new IllegalStateException(); }
if (position == first)
{
removeFirst();
}
else
{
previous.next = position.next;
}
if (___) ___;
position = previous;
isAfterNext = false;
}
What should be filled in for the two ___?