Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating from the end of a list

Tags:

java

list

I know that we can iterate over the list in the reverse order as follows:

List<Object> lst;
ListIterator<Object> i = lst.listIterator(lst.size());

But is it efficient if lst is a LinkedList? I mean when we obtain the ListIterator pointing to the end of the list, does the implementation iterate over the list from the begging to the list.size() position (takes O(n) time, where n is a size of the list)?

If it does, is there a way to avoid it?

like image 642
St.Antario Avatar asked Jan 27 '26 06:01

St.Antario


1 Answers

The javadoc states that LinkedList is a doubly-linked list, so I would expect descendingIterator(), which return an iterator pointing to the tail of the list, to be O(1). Note that descendingIterator is from the Deque interface.

Now it is difficult to say whether the statement lst.listIterator(lst.size()) is also O(1), because it is not documented if listIterator method optimize the fact that the next element from lst.size() is the tail.

like image 104
UmNyobe Avatar answered Jan 29 '26 18:01

UmNyobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!