javadoubly-linked-list

Syntax to move backwards in LinkedList?


I know that LinkedLists are implemented in a doubly-linked way, so each node has a next and a previous pointer. However, I couldn't find what syntax to use to access the previous nodes. I looked in the Java API, and there is a method to iterate through a linkedlist backwards. That to me, implies that there is an easy way to access previous nodes.

I am trying to design an experiment to prove that LinkedLists isn't just a singly-linked list, but I can't think of how to do so without moving backwards in linkedlists.

How do I move backwards in a LinkedList?


Solution

  • LinkedList has a listIterator(int) method. So you can use:

    // Start at the end...
    ListIterator<Foo> iterator = list.listIterator(list.size());
    while (iterator.hasPrevious()) {
        Foo foo = iterator.previous();
    }
    

    That doesn't prove that it's a doubly-linked list - that could be implemented very inefficiently in a single-linked list, for example - but that's how I'd go about iterating over a linked list backwards.