0

# Reverse arraylist

Hi every one.... How can i reverse an arraylist in java without using any methods.... Like Collections.reverse () ; and etc...

1/5/2020 2:56:35 PM

AM-78

+5

Honestly, just use in-builts. Usually they're built by smarter people who could do it better than you could.

+5

Denise Roßberg Yeah i do know that, but i am talking about the way of thinking. His way is the standard way of reversing an array, yours takes O(n) but still it is creative ^ ^

+4

You don't need a second list. for(int i = list.size() - 1; i >= 0; i--){ //add the value to the list list.add(list.get(i)); //remove value list.remove(i); } E.g. 1 2 3 4 index = 3, value = 4 1 2 3 4 4 (add 4 & remove 4 at index 3) -> 1 2 3 4 index = 2, value = 3 1 2 3 4 3 (add 3 & remove 3 at index 2) -> 1 2 4 3 index = 1, value = 2 1 2 4 3 2 (add 2, remove 2 at index 1) -> 1 4 3 2 index = 0, value = 1 1 4 3 2 1 (add 1 && remove 1 at index 0) -> 4 3 2 1 -> done

+4

List reversing using variable value swap method: https://code.sololearn.com/c3yfniOgu249/?ref=app

+3

Denise Roßberg UwU That's cool algorithm π

+2

You can make a new list: Arraylist newlist = new Arraylist() for (int i = list.size() -1 ; i >= 0; i --){ newlist.add(list.get(i)); } But maybe there are better solutions

0

,.., Thanks. But Seb TheS code is better. Look at the 1 2 3 4 example. With my solution you need 4 steps. But swapping the elements needs only 2 steps: 4 2 3 1 4 3 2 1

-1

Umar