C语言设计一个汽车牌照管理系统,要求利用链式基数排序方法实现车牌号的排序,然后利用折半查找法实现对汽车牌照按关键字进行查找
时间: 2024-03-15 16:41:29 浏览: 98
好的,这是一个基于C语言的汽车牌照管理系统,实现了链式基数排序和折半查找法。以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义车牌号结构体
typedef struct LicensePlate {
char code[10];
struct LicensePlate *next;
} LicensePlate;
void radixSort(LicensePlate **head, int digit) {
// 判断是否已经排完
if (digit <= 0) {
return;
}
// 基数排序
LicensePlate *buckets[10] = { 0 };
LicensePlate *current = *head;
while (current != NULL) {
int index = current->code[digit - 1] - '0';
if (buckets[index] == NULL) {
buckets[index] = current;
} else {
LicensePlate *tmp = buckets[index];
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = current;
}
current = current->next;
}
// 将排序后的链表重新连接起来
int i;
for (i = 0; i < 10; i++) {
if (buckets[i] != NULL) {
current = buckets[i]->next;
while (current != NULL) {
if (current->code[digit - 1] - '0' != i) {
break;
}
current = current->next;
}
buckets[i]->next = NULL;
radixSort(&buckets[i], digit - 1);
if (*head == NULL) {
*head = buckets[i];
current = buckets[i];
} else {
current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = buckets[i];
}
}
}
}
LicensePlate *search(LicensePlate *head, char *target) {
// 折半查找
int left = 0, right = 0;
LicensePlate *current = head;
while (current != NULL) {
right++;
current = current->next;
}
while (left <= right) {
int mid = (left + right) / 2;
current = head;
int i;
for (i = 0; i < mid; i++) {
if (current == NULL) {
return NULL;
}
current = current->next;
}
if (current == NULL) {
return NULL;
}
int compare = strcmp(current->code, target);
if (compare == 0) {
return current;
} else if (compare < 0) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return NULL;
}
int main() {
// 初始化链表
LicensePlate *head = NULL;
LicensePlate *current = NULL;
int i;
for (i = 0; i < 5; i++) {
LicensePlate *plate = (LicensePlate *)malloc(sizeof(LicensePlate));
printf("请输入第%d个车牌号:", i + 1);
scanf("%s", plate->code);
plate->next = NULL;
if (head == NULL) {
head = plate;
current = head;
} else {
current->next = plate;
current = current->next;
}
}
// 链式基数排序
radixSort(&head, 7);
// 打印排序后的链表
printf("排序后的车牌号:");
current = head;
while (current != NULL) {
printf("%s ", current->code);
current = current->next;
}
printf("\n");
// 查找车牌号
char target[10];
printf("请输入要查找的车牌号:");
scanf("%s", target);
current = search(head, target);
if (current == NULL) {
printf("未找到车牌号为%s的车辆\n", target);
} else {
printf("找到车牌号为%s的车辆\n", target);
}
return 0;
}
```
这个程序中,我们首先定义了一个 `LicensePlate` 结构体,表示车牌号码。在 `main` 函数中,我们通过循环输入 5 个车牌号,并将它们组成一个链表。
然后我们使用链式基数排序对这个链表进行排序。排序的过程中,我们使用了 `buckets` 数组来存储每个数字的链表。然后我们将排序后的链表重新连接起来。
最后,我们通过折半查找法来查找指定的车牌号。在 `search` 函数中,我们先计算出链表的长度,然后在循环中不断取中间的节点进行比较,直到找到目标节点或者链表被遍历完。
当然,这个程序还有很多可以改进的地方。例如,我们可以将输入车牌号和打印车牌号的代码封装成函数,提高代码的可读性。
阅读全文