(Implement a doubly linked list) The MyLinkedList class used in Listing 26.6 is
ID: 3761310 • Letter: #
Question
(Implement a doubly linked list) The MyLinkedList class used in Listing 26.6 is a one-way directional linked list that enables one-way traversal of the list. Modify the Node class to add the new field name previous to refer to the previous node in the list, as follows:
public class Node<E> {
E element;
Node<E> next;
Node<E> previous;
public Node(E e) {
element = e;
}
}
Implement a new class named MyTwoWayLinkedList that uses a doubly linked list to store elements. The MyLinkedList class in the text extends MyAbstractList. Define MyTwoWayLinkedList to extend the java.util.AbstractSequentialList class. You need to implement the methods listIterator() and listIterator(int index). Both return an instance of java.util.ListIterator<E>. The former sets the cursor to the head of the list and the latter to the element at the specified index.
Explanation / Answer
private class TwoWayLinkedListIterator<E> implements ListIterator<E>
{
private Node<E> current = head.next;
private Node<E> lastAccessed = null;
private int index = 0;
public boolean hasNext()
{
return index < size;
}
public boolean hasPrevious()
{
return index > 0;
}
public int previousIndex()
{
return index - 1;
}
public int nextIndex()
{
return index;
}
public E next()
{
if (!hasNext())
throw new NoSuchElementException();
lastAccessed = current;
E item = current.element;
current = current.next;
index++;
return item;
}
public E previous()
{
if (!hasPrevious())
throw new NoSuchElementException();
current = current.previous;
index--;
lastAccessed = current;
return current.element;
}
public void set(E value)
{
if(lastAccessed == null)
throw new IllegalStateException();
lastAccessed.element = value;
}
public void remove()
{
if (lastAccessed == null)
throw new IllegalStateException();
Node<E> x = lastAccessed.previous;
Node<E> y = lastAccessed.next;
x.next = y;
y.previous = x;
size--;
if (current == lastAccessed)
current = y;
else
index--;
lastAccessed = null;
}
public void add(E value)
{
Node<E> x = current.previous;
Node<E> y = new Node(value);
Node<E> z = current;
x.next = y;
y.next = z;
z.previous = y;
y.previous = x;
size++;
index++;
lastAccessed = null;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.