用C语言请设计一个顺序表,存储26个英文元素的大写字母表:(A,B,C,D…),完成线性表的初始化创建、按内容查询、插入、删除、输出表中信息五个操作。
时间: 2024-09-10 18:24:13 浏览: 201
在C语言中,我们可以使用结构体和动态内存分配来实现一个简单的顺序表数据结构,用于存储大写的英文字母。首先,我们定义一个结构体表示字符节点,然后实现所需的操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 结构体代表单个节点
typedef struct {
char letter;
struct Node* next; // 指向下一个节点的指针
} Node;
// 链表头结点
typedef struct {
Node* head;
int size;
} AlphabetList;
// 初始化顺序表
void init_list(AlphabetList* list) {
list->head = NULL;
list->size = 0;
}
// 插入字母
void insert_letter(AlphabetList* list, char letter) {
if (list->head == NULL) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->letter = letter;
newNode->next = NULL;
list->head = newNode;
} else {
Node* current = list->head;
while (current->next != NULL && current->next->letter < letter) {
current = current->next;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->letter = letter;
newNode->next = current->next;
current->next = newNode;
list->size++;
}
}
// 查找字母并返回其索引(从0开始)
int find_letter(AlphabetList* list, char letter) {
Node* current = list->head;
for (int i = 0; i < list->size; i++) {
if (current->letter == letter) {
return i;
}
current = current->next;
}
return -1; // 如果未找到则返回-1
}
// 删除指定字母
void delete_letter(AlphabetList* list, char letter) {
if (list->head == NULL) return;
if (list->head->letter == letter) {
Node* temp = list->head;
list->head = list->head->next;
free(temp);
list->size--;
return;
}
Node* prev = list->head;
Node* current = list->head->next;
while (current != NULL && current->letter != letter) {
prev = current;
current = current->next;
}
if (current == NULL) return; // 如果没找到就直接返回
prev->next = current->next;
free(current);
list->size--;
}
// 输出字母列表
void print_list(AlphabetList* list) {
Node* current = list->head;
printf("Sorted Alphabet List:\n");
while (current != NULL) {
printf("%c ", current->letter);
current = current->next;
}
printf("\n");
}
int main() {
AlphabetList alphabet;
init_list(&alphabet);
// 添加字母到列表
for (char c = 'A'; c <= 'Z'; c++) {
insert_letter(&alphabet, c);
}
// 输出初始列表
print_list(&alphabet);
// 查询特定字母
char searchLetter = 'B';
int index = find_letter(&alphabet, searchLetter);
if (index != -1) {
printf("'%c' is at index %d.\n", searchLetter, index);
} else {
printf("'%c' not found in the list.\n", searchLetter);
}
// 删除一个字母
delete_letter(&alphabet, 'D');
// 输出修改后的列表
print_list(&alphabet);
return 0;
}
```
阅读全文
相关推荐


















