xTopShelfx xTopShelfx - 1 year ago 73
Java Question

Traversing a LinkedList tail to head

I need to traverse through this custom linked list implementation and display its contents:

  • from head to tail,

  • then again from tail to head.

I was able to display the lists contents from head to tail pretty easily with a for loop:

for (AccountRecordSerializable account : list) {

and everything works fine. Now I am trying to reverse that. In provided LinkedList class to use which has a LinkedListIterator class inside it as well. The iterator class has methods such as
which I know can be used to do so, but I'm not quite sure how to use that iterator through my LinkedList to do so.

Is there a simpler way as I had done before to reverse this? Or how would I use the Iterator class to iterate through my list so that it performs the task?

I apologize if this doesn't make any sense... let me know if you need clarifications..Thanks.

Answer Source

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();) {


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 readObjectsand 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download