用C语言建立一个线性表,要求有初始化,插入,删除,查找,销毁这5个基本操作
时间: 2024-05-22 17:16:55 浏览: 106
#include <stdio.h>
#include <stdlib.h>
// 定义线性表结构体
typedef struct {
int *data; // 数据数组指针
int length; // 线性表长度
int size; // 分配的存储空间大小
} List;
// 初始化线性表
void initList(List *list) {
list->data = (int*)malloc(sizeof(int) * 10); // 初始分配10个存储空间
list->length = 0;
list->size = 10;
}
// 插入数据
void insertList(List *list, int index, int value) {
// 判断是否需要扩容
if (list->length == list->size) {
list->data = (int*)realloc(list->data, sizeof(int) * (list->size + 10));
list->size += 10;
}
// 插入数据
for (int i = list->length - 1; i >= index; i--) {
list->data[i+1] = list->data[i];
}
list->data[index] = value;
list->length++;
}
// 删除数据
void deleteList(List *list, int index) {
// 删除数据
for (int i = index; i < list->length-1; i++) {
list->data[i] = list->data[i+1];
}
list->length--;
}
// 查找数据
int findList(List *list, int value) {
for (int i = 0; i < list->length; i++) {
if (list->data[i] == value) {
return i;
}
}
return -1;
}
// 销毁线性表
void destroyList(List *list) {
free(list->data);
list->data = NULL;
list->length = 0;
list->size = 0;
}
int main() {
List list;
initList(&list);
insertList(&list, 0, 1);
insertList(&list, 1, 2);
insertList(&list, 2, 3);
insertList(&list, 3, 4);
insertList(&list, 4, 5);
for (int i = 0; i < list.length; i++) {
printf("%d ", list.data[i]);
}
printf("\n");
deleteList(&list, 2);
for (int i = 0; i < list.length; i++) {
printf("%d ", list.data[i]);
}
printf("\n");
int index = findList(&list, 4);
printf("index of 4: %d\n", index);
destroyList(&list);
return 0;
}
阅读全文