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?
Use import java.util.Collections;
Collections.reverse(list);
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());
see java.util.Collections.reverse(List list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With