Java Reference
In-Depth Information
E result = current.data;
current = current.next;
removeOK = true;
return result;
}
For the
remove
method, your code will look like this:
public void remove() {
if (!removeOK) {
throw new IllegalStateException();
}
ListNode<E> prev2 = current.prev.prev;
prev2.next = current;
current.prev = prev2;
size--;
removeOK = false;
}
Notice that, to remove a node, you have to reset both a
next
and a
prev
pointer in
the list because now you are working with a doubly linked list.
Before we leave the subject of iterators, you should consider briefly how to imple-
ment the
addAll
method for your
LinkedList
class. Keep in mind that its header
will refer to your
List
interface:
public void addAll(List<E> other) {
...
}
You have to write this code in such a way that it can take either a
LinkedList
or
an
ArrayList
as a parameter. That means that you have to use methods mentioned in
the interface. One misguided approach would be to use a
for
loop and repeatedly
call
get
to retrieve each element:
// inefficient implementation of addAll method
public void addAll(List<E> other) {
for (int i = 0; i < other.size(); i++) {
add(other.get(i));
}
}
This code will work, but it will be extremely inefficient when
other
is a
LinkedList
. Each time you call the
get
method, you have to start at the front of
the list and skip nodes until you get to the right spot. It is much better to use an iter-
ator to solve this problem. You can make it particularly simple by using a for-each
Search WWH ::
Custom Search