Coding to place the array upside down using Java list's sublist

Asked 2 years ago, Updated 2 years ago, 53 views

I wrote two functions that put the list upside down and turned them around to test them in the main function. It seems that certain numbers are constantly added to the arr list in functions created using the list. So I think if you test the second function with the same input, it will be printed differently. I wonder if there is any other way to slice the list other than the list, and I don't know why it is added...Help me!!

public static List<Integer> reverse(List<Integer> arr) {
    if (arr.size() == 1) {
        return arr;
    }
    int base = arr.get(0);
    arr = arr.subList(1, arr.size());
    arr = reverse(arr); // I wonder why it comes with a base value when reverse(arr) is not substituted for arr
    arr.add(base);
    return arr;
}

public static List<Integer> reverse(List<Integer> arr, int start, int end) {
    if (start < end - 1) {
        int base = arr.get(start);
        arr.set(start, arr.get(end - 1));
        arr.set(end - 1, base);
        return reverse(arr, start + 1, end - 1);
    } } else {
        return arr;
    }
}

public static void main(String[] args) {
    List<Integer> arr = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
    List<Integer> arr2 = new ArrayList<>();
    List<Integer> arr3 = new ArrayList<>();
    arr2 = reverse(arr);
    for (int a : arr2) {
        System.out.print(a + " ");
    }
    System.out.println();

    arr3 = reverse(arr, 0, 6);

    for (int a : arr3) {
        System.out.print(a + " ");
    }
}

}

java algorithm

2022-09-20 08:41

1 Answers

The reason why the output value is strange is that the original list arrr has been modified. It looks like something is attached when you reuse the transformed object.

Keep arrr original and try to fix it by creating and dealing with replications.

For studying, it is close to Cheat, but there is a java.util.Collections.reverse() method.

List<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
Collections.reverse(arr); // Method by which the forwarding factor is mutated    
System.out.println(arr); // [6, 5, 4, 3, 2, 1]


2022-09-20 08:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.