publicclassSolution {
publicstaticvoidreverseArray(int[] arr) {
int start = 0;
int end = arr.length- 1;
while (start < end) {
// Swap the elements at start and endint temp = arr[start];
arr[start]= arr[end];
arr[end]= temp;
// Move the pointers towards the center start++;
end--;
}
}
publicstaticvoidmain(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Original array: "+ Arrays.toString(arr));
reverseArray(arr);
System.out.println("Reversed array: "+ Arrays.toString(arr));
// Expected output: [5, 4, 3, 2, 1] }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defreverse_array(self, arr: List[int]) ->None:
start =0 end = len(arr) -1while start < end:
# Swap the elements at start and end arr[start], arr[end] = arr[end], arr[start]
# Move the pointers towards the center start +=1 end -=1
publicclassSolution {
publicstaticvoidreverseArray(int[] arr) {
Stack<Integer> stack =new Stack<>();
// Push all elements of the array onto the stackfor (int num : arr) {
stack.push(num);
}
// Pop all elements from the stack and put them back into the arrayint index = 0;
while (!stack.isEmpty()) {
arr[index++]= stack.pop();
}
}
publicstaticvoidmain(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Original array: "+ Arrays.toString(arr));
reverseArray(arr);
System.out.println("Reversed array: "+ Arrays.toString(arr));
// Expected output: [5, 4, 3, 2, 1] }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defreverse_array(self, arr: List[int]) ->None:
stack = []
# Push all elements of the array onto the stackfor num in arr:
stack.append(num)
# Pop all elements from the stack and put them back into the array index =0while stack:
arr[index] = stack.pop()
index +=1