10801:半开区间数组反转
题目
仅使用指针运算和解引用,原地反转一个整数数组。空数组不得产生无效访问。
解析
当元素少于两个时,数组已经满足要求。否则让 left 指向首元素,让 right 指向末元素;交换两端元素后同时向中间移动,直到两个指针相遇或交错。
只有在 count >= 2 时才计算 items + count - 1,因此空数组允许传入 NULL,也不会对空指针执行算术。
解析
c
#include <stddef.h>
void reverse_i32(int *items, size_t count) {
if (count < 2) {
return;
}
int *left = items;
int *right = items + count - 1;
while (left < right) {
int temporary = *left;
*left = *right;
*right = temporary;
++left;
--right;
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19