-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathReverseAnySequence.java
48 lines (40 loc) · 1.32 KB
/
ReverseAnySequence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package by.andd3dfx.collections;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
/**
* Examples how to reverse any list using different methods
*
* @see <a href="https://youtu.be/Ql6JGqcSiNk">Video solution</a>
*/
public class ReverseAnySequence {
public static <T> List<T> reverseUsingStack(List<T> list) {
var stack = new ArrayDeque<T>();
list.forEach(stack::push);
return stack.stream().toList();
}
public static <T> List<T> reverseUsingRecursion(List<T> list) {
if (list.size() == 1) {
return list;
}
var firstItem = list.get(0);
List<T> subList = list.subList(1, list.size());
return compose(reverseUsingRecursion(subList), firstItem);
}
private static <T> List<T> compose(List<T> list, T item) {
List<T> result = new ArrayList<>(list);
result.add(item);
return result;
}
public static <T> List<T> reverseUsingLoop(List<T> list) {
for (int i = 0; i < list.size() / 2; i++) {
swap(list, i, list.size() - 1 - i);
}
return list;
}
private static <T> void swap(List<T> list, int i, int j) {
var tmp = list.get(i);
list.set(i, list.get(j));
list.set(j, tmp);
}
}