Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 932
user1476390 Avatar asked Mar 24 '26 19:03

user1476390


2 Answers

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.

like image 94
Jon Skeet Avatar answered Mar 27 '26 09:03

Jon Skeet


You can call LinkedList.listIterator() which will return an iterator that you can use to go both directions (next/previous)

like image 45
Nir Alfasi Avatar answered Mar 27 '26 08:03

Nir Alfasi