可以利用棧來實現數組的逆序操作,具體步驟如下:
以下是一個示例代碼:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int top;
int capacity;
int *array;
} Stack;
Stack* createStack(int size) {
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
stack->capacity = size;
stack->array = (int*)malloc(sizeof(int) * size);
return stack;
}
void push(Stack *stack, int data) {
stack->array[++stack->top] = data;
}
int pop(Stack *stack) {
return stack->array[stack->top--];
}
void reverseArray(int arr[], int size) {
Stack *stack = createStack(size);
for (int i = 0; i < size; i++) {
push(stack, arr[i]);
}
for (int i = 0; i < size; i++) {
arr[i] = pop(stack);
}
free(stack->array);
free(stack);
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, size);
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
以上代碼通過利用棧實現了數組的逆序操作,輸出結果為:5 4 3 2 1。