1、双指针法
使用两个指针,一个指向数组的开头,一个指向数组的末尾,然后交换它们的值,直到两个指针相遇。
#include <stdio.h> void reverseArray(int arr[], int n) { int start = 0; int end = n - 1; while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
2、递归法
使用递归来反转数组,通过交换第一个元素和最后一个元素,然后递归地处理剩余的子数组。
#include <stdio.h> void reverseArrayRecursive(int arr[], int start, int end) { if (start >= end) return; int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; reverseArrayRecursive(arr, start + 1, end - 1); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); reverseArrayRecursive(arr, 0, n - 1); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
3、辅助数组法
使用一个辅助数组来存储原数组的反转版本,然后将辅助数组的值复制回原数组。
#include <stdio.h> void reverseArrayWithAux(int arr[], int n) { int aux[n]; for (int i = 0; i < n; i++) { aux[n - 1 - i] = arr[i]; } for (int i = 0; i < n; i++) { arr[i] = aux[i]; } } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); reverseArrayWithAux(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
4、栈法
使用栈来反转数组,将数组元素依次压入栈中,然后再依次弹出到原数组中。
#include <stdio.h> #include <stdlib.h> typedef struct Stack { int top; unsigned capacity; int* array; } Stack; Stack* createStack(unsigned capacity) { Stack* stack = (Stack*)malloc(sizeof(Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int*)malloc(stack->capacity * sizeof(int)); return stack; } int isFull(Stack* stack) { return stack->top == stack->capacity - 1; } int isEmpty(Stack* stack) { return stack->top == -1; } void push(Stack* stack, int item) { if (isFull(stack)) return; stack->array[++stack->top] = item; } int pop(Stack* stack) { if (isEmpty(stack)) return -1; return stack->array[stack->top--]; } void reverseArrayWithStack(int arr[], int n) { Stack* stack = createStack(n); for (int i = 0; i < n; i++) { push(stack, arr[i]); } for (int i = 0; i < n; i++) { arr[i] = pop(stack); } free(stack->array); free(stack); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); reverseArrayWithStack(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
5、STL库函数
在C++中,可以使用STL中的 reverse
函数来反转数组。在C语言中,我们可以实现类似的功能。
#include <stdio.h> void reverseArraySTL(int arr[], int n) { for (int i = 0; i < n / 2; i++) { int temp = arr[i]; arr[i] = arr[n - 1 - i]; arr[n - 1 - i] = temp; } } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); reverseArraySTL(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }