Data Structures, Algorithms, & Applications in Java
Chapter 6, Exercise 57
The code for
DoubleIterator
is given below.
public class DoublyLinkedListWithDoubleIterator extends DoublyLinkedList
{
public DoubleIterator doubleIterator()
{return new DoubleIterator();}
/** two way iterator */
private class DoubleIterator implements Iterator
{
// data member
private DoubleNode nextNode;
// constructor
public DoubleIterator()
{nextNode = firstNode;}
// methods
/** @return true iff list has a next element */
public boolean hasNext()
{return nextNode != null;}
/** @return true iff list has a previous element */
public boolean hasPrevious()
{return (size > 1) && (nextNode != firstNode)
&& (nextNode != firstNode.next);}
/** @return next element in list
* @throws NoSuchElementException
* when there is no next element */
public Object next()
{
if (nextNode != null)
{
Object elementToReturn = nextNode.element;
nextNode = nextNode.next;
return elementToReturn;
}
else throw new NoSuchElementException("No next element");
}
/** @return previous element in list
* @throws NoSuchElementException
* when there is no previous element */
public Object previous()
{
if ((size > 1) && (nextNode != firstNode)
&& (nextNode != firstNode.next))
{
if (nextNode == null)
// previous node is 2nd last node of list
nextNode = lastNode;
else
// previous node is 2 nodes left of current nextNode
nextNode = nextNode.previous;
return nextNode.previous.element;
}
else throw new NoSuchElementException("No previous element");
}
/** unsupported method */
public void remove()
{
throw new UnsupportedOperationException
("remove not supported");
}
}
}
The test program and output are in the files
DoublyLinkedListWithDoubleIterator.*.