Reputation: 535
Q: Given a list, reverse the order of its elements (don't use collections)
Here is my solution:
public static <T> void reverse(List<T> list) {
if (list.size() > 0) {
T t;
t = list.get(0);
list.remove(0);
reverse(list);
list.add(t);
}
}
It is working as expected, but I want to know if this recursive method is an efficient way of reversing a list
Upvotes: 0
Views: 99
Reputation: 49803
Reversing the list in place:
public static <T> void reverse(List<T> list) {
int a =0, b = list.size()-1;
while ( a < b ) {
T a_val = list.get(a);
list.set( a, list.get(b) );
list.set( b, a_val );
a++;
b--;
}
}
Upvotes: 1