逆置数组
时间: 2023-08-29 10:06:02 浏览: 68
逆置数组就是将数组中的元素顺序颠倒过来。可以使用两个指针分别指向数组的头和尾,然后交换它们所指向的元素,直到两个指针相遇为止。
以下是一个 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语言pta
以下是逆置数组的C语言代码示例:
```c
#include <stdio.h>
void reverseArray(int arr[], int start, int end) {
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int start = 1, end = 3;
int len = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
reverseArray(arr, start, end);
printf("\nReversed array: ");
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
该代码定义了一个 `reverseArray` 函数,用于部分逆置数组。在 `main` 函数中,我们声明了一个整数数组 `arr`,并调用 `reverseArray` 函数来部分逆置数组中索引从 `start` 到 `end` 的元素。最后,我们输出逆置后的数组。
逆置数组reverse
以下是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]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)