Новый курс! Каждый программист должен знать генеративный ИИ!
0

# Reverse arraylist

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

5th Jan 2020, 2:56 PM
AM-78
8 ответов
+ 6
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 ^ ^
5th Jan 2020, 7:14 PM
Anon Fox
+ 5
Honestly, just use in-builts. Usually they're built by smarter people who could do it better than you could.
5th Jan 2020, 3:13 PM
👑 Prometheus 🇸🇬
+ 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
5th Jan 2020, 3:33 PM
Denise Roßberg
+ 4
List reversing using variable value swap method: https://code.sololearn.com/c3yfniOgu249/?ref=app
5th Jan 2020, 5:13 PM
Seb TheS
+ 4
Denise Roßberg UwU That's cool algorithm 😍
5th Jan 2020, 7:06 PM
Anon Fox
+ 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
5th Jan 2020, 3:06 PM
Jnn
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
5th Jan 2020, 7:11 PM
Denise Roßberg
- 1
Umar
5th Jan 2020, 7:18 PM
Umer Rabi
Актуальное сегодня
c++ help