在算法設計中,逆序排列是一種常見的操作。它可以應用于各種數據結構和場景,例如數組、鏈表、字符串等。下面是一些使用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 n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
reverseArray(arr, 0, n - 1);
printf("Reversed array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
#include<stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* reverseList(struct Node* head) {
struct Node *prev = NULL;
struct Node *current = head;
struct Node *next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
void printList(struct Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
struct Node* temp;
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = n - 1; i >= 0; i--) {
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = arr[i];
temp->next = head;
head = temp;
}
printf("Original list: ");
printList(head);
head = reverseList(head);
printf("Reversed list: ");
printList(head);
return 0;
}
#include<stdio.h>
#include<string.h>
void reverseString(char* str) {
int len = strlen(str);
char temp;
for (int i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
}
int main() {
char str[] = "Hello, world!";
printf("Original string: %s\n", str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
這些示例展示了如何在C語言中實現逆序排列。你可以根據需要修改這些代碼以適應不同的數據結構和場景。