Reputation: 54094
I want to reverse a java.util.LinkedList<Integer>
using the available methods.
Looking in the methods provided and the Iterators
I couldn't see an option other than the following:
int i = list.size();
int pos = 0;
while(i-- > 1){
Integer n = list.removeLast();
list.add(pos++, n);
}
But surely there must be a better way. I mean it is not a good idea to modify a list outside of an iterator, but I couldn't see how I could use one here without having to create a new list.
Is there a better way?
Upvotes: 7
Views: 8102
Reputation: 17445
There's an api method for that.
Collections.reverse(yourList);
See http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#reverse%28java.util.List%29.
If for some reason you want to do it yourself, this seems the best way:
List<T> reversed = new LinkedList<T>();
while(!yourList.isEmpty()) reversed.add(yourList.removeLast());
Upvotes: 3