用C语言实现顺序表的链式存储并实现增删改查功能,要求有菜单
时间: 2024-09-15 21:10:18 浏览: 46
要使用C语言实现顺序表(Array-based)的链式存储并实现基本的操作(增删改查),通常我们会使用指针来模拟链表的行为。然而,顺序表(也称为线性表)实际上不需要使用链式结构,因为它们可以通过数组直接访问元素。这里我们将创建一个简单的顺序表,并提供基本的功能,但请注意,这并不是传统意义上的链表。
首先,我们需要定义一个顺序表结构体:
```c
#include <stdio.h>
typedef struct {
int data[100]; // 假设我们有一个大小为100的数组用于存储数据
int size; // 记录实际使用的空间,初始值为0
} SequentialList;
```
接下来,创建几个函数来实现操作:
1. 初始化顺序表:
```c
void init_list(SequentialList* list) {
list->size = 0;
}
```
2. 插入元素(在列表末尾):
```c
void insert_at_end(SequentialList* list, int value) {
if (list->size == sizeof(list->data)) {
printf("Error: List is full.\n");
return;
}
list->data[list->size] = value;
list->size++;
}
```
3. 删除元素(查找指定位置并删除):
```c
void delete_at_index(SequentialList* list, int index) {
if (index >= 0 && index < list->size) {
for (int i = index; i < list->size - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->size--;
} else {
printf("Error: Index out of range.\n");
}
}
```
4. 修改元素(查找指定位置并修改):
```c
void update_at_index(SequentialList* list, int index, int new_value) {
if (index >= 0 && index < list->size) {
list->data[index] = new_value;
} else {
printf("Error: Index out of range.\n");
}
}
```
5. 查找元素:
```c
int find_element(const SequentialList* list, int value) {
for (int i = 0; i < list->size; i++) {
if (list->data[i] == value) {
return i;
}
}
return -1; // 如果没有找到,则返回-1
}
```
6. 主菜单函数:
```c
void menu(SequentialList* list) {
while (true) {
printf("\nSequential List Menu:\n");
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Update\n");
printf("4. Find\n");
printf("5. Exit\n");
int choice;
scanf("%d", &choice);
switch (choice) {
case 1:
int value;
printf("Enter value to insert: ");
scanf("%d", &value);
insert_at_end(list, value);
break;
case 2:
int index;
printf("Enter index to delete: ");
scanf("%d", &index);
delete_at_index(list, index);
break;
case 3:
int index, new_value;
printf("Enter index to update: ");
scanf("%d", &index);
printf("New value: ");
scanf("%d", &new_value);
update_at_index(list, index, new_value);
break;
case 4:
int search_value;
printf("Enter value to find: ");
scanf("%d", &search_value);
int found_index = find_element(list, search_value);
if (found_index != -1)
printf("Found at index %d\n", found_index);
else
printf("Value not found.\n");
break;
case 5:
printf("Exiting...\n");
exit(0); // 退出程序
default:
printf("Invalid choice. Please try again.\n");
}
}
}
```
现在你可以创建一个`SequentialList`实例并运行主菜单:
```c
int main() {
SequentialList my_list;
init_list(&my_list);
menu(&my_list);
return 0;
}
```
阅读全文