给我提供一个能初始化、建立、求表长、输出、插入、查找、删除功能的线性表c语言结构
时间: 2023-10-16 10:07:43 浏览: 76
基于C语言实现线性表的建立、插入、删除、查找等基本操作.zip
typedef struct {
int* data; // 存储数据的数组
int length; // 线性表长度
int capacity; // 线性表容量
} List;
// 初始化线性表
void initList(List* list, int capacity) {
list->data = (int*)malloc(sizeof(int) * capacity);
list->length = 0;
list->capacity = capacity;
}
// 建立线性表
void createList(List* list, int* arr, int n) {
if (n > list->capacity) {
printf("Error: The capacity of the list is not enough.\n");
return;
}
for (int i = 0; i < n; i++) {
list->data[i] = arr[i];
}
list->length = n;
}
// 求表长
int getLength(List* list) {
return list->length;
}
// 输出线性表
void printList(List* list) {
printf("[");
for (int i = 0; i < list->length; i++) {
printf("%d", list->data[i]);
if (i != list->length - 1) {
printf(", ");
}
}
printf("]\n");
}
// 插入元素
void insert(List* list, int index, int value) {
if (index < 0 || index > list->length) {
printf("Error: Index out of range.\n");
return;
}
if (list->length == list->capacity) {
printf("Error: The list is full.\n");
return;
}
for (int i = list->length - 1; i >= index; i--) {
list->data[i + 1] = list->data[i];
}
list->data[index] = value;
list->length++;
}
// 查找元素
int find(List* list, int value) {
for (int i = 0; i < list->length; i++) {
if (list->data[i] == value) {
return i;
}
}
return -1;
}
// 删除元素
void remove(List* list, int index) {
if (index < 0 || index >= list->length) {
printf("Error: Index out of range.\n");
return;
}
for (int i = index + 1; i < list->length; i++) {
list->data[i - 1] = list->data[i];
}
list->length--;
}
阅读全文