逆置数组reverse
时间: 2023-11-24 20:51:22 浏览: 134
以下是Python中逆置数组的两种方法:
1.使用reverse()函数
```python
arr = [1, 2, 3, 4, 5]
arr.reverse()
print(arr) # 输出:[5, 4, 3, 2, 1]
```
2.使用切片
```python
arr = [1, 2, 3, 4, 5]
arr = arr[::-1]
print(arr) # 输出:[5, 4, 3, 2, 1]
```
相关问题
逆置数组
逆置数组就是将数组中的元素顺序颠倒过来。可以使用两个指针分别指向数组的头和尾,然后交换它们所指向的元素,直到两个指针相遇为止。
以下是一个 C 语言实现的逆置数组的示例代码:
```c
#include <stdio.h>
void reverse(int arr[], int size) {
int i, j;
for (i = 0, j = size - 1; i < j; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
reverse(arr, size);
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果为:`5 4 3 2 1`。
c++逆置数组reserve
Sure, here's a sample code for reversing an array in C:
```
#include <stdio.h>
void reverse(int arr[], int n) {
int temp;
for (int i = 0; i < n/2; i++) {
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
reverse(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
This code uses a simple swapping technique to reverse the elements of an array. The `reverse` function takes an array and its size as input, and swaps the first and last elements, then the second and second-to-last elements, and so on, until the entire array is reversed. The `main` function initializes an array, calls the `reverse` function, and then prints the reversed array.
阅读全文