Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to reverse a java.util.LinkedList (in place if possible)

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?

like image 566
Cratylus Avatar asked Apr 23 '12 09:04

Cratylus


3 Answers

Use import java.util.Collections;

Collections.reverse(list);
like image 152
ehanoc Avatar answered Jan 20 '23 12:01

ehanoc


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());
like image 27
Joeri Hendrickx Avatar answered Jan 20 '23 10:01

Joeri Hendrickx


see java.util.Collections.reverse(List list)

like image 29
tanyehzheng Avatar answered Jan 20 '23 12:01

tanyehzheng