The Java LinkedList implements interface Deque that provides method descendingIterator.
Returns an iterator over the elements in this deque in reverse sequential order. The elements will be returned in order from last (tail) to first (head).
My advise for you is to implement that interfaces in your class, and the obtain reversed iterator.
The linked list is data structure with some properties that you should use to get the implementation. The typical construction of linked list is that an element points to next one. In your case you have implementation that supports double linked list.
private int size = 0; // size can never be < 0
private DLNode<E> head;
private DLNode<E> tail;
In your code you have DLNode
that stand for Double Linked Node. This means that you can move from head
to tail
by using hasNex()
and from tail to head using hasPrevious()
.
In your class you have the class LinkedListIterator
, that you can obtain with this method:
public ListIterator<E> listIterator(int index) {
if ((index < 0) || (index > size)) {
throw new IndexOutOfBoundsException("index " + index+ " is out of range: 0 to " + size);
}
return new LinkedListIterator<E>(index);
}
So to print your elements you could do it like this.
public <T> void printLinkedListFromHead(LinkedList<T> list) {
for(ListIterator<T> iterator = list.listIterator(0); iterator.hasNext();) {
System.out.println(iterator.next());
}
}
You should also create a separate class for your code, where you will put your code that contextually does not belong to the linked list implementation. The method readObjects
and writeObjects
do not belong to class. same as main.
If you would have standard Java LinkedList you could wrote something like this:
public <T> reversePrint(Deque deque) {
for (Iterator<T> iterator = deque.descendingIterator(); iterator .hasNext();){
System.out.println(iterator .next());
}
}
To narrow the scope of iterator promote for loop than while.