用c语言写一个可变数组的线性表,要求包含数据的增删改查功能。
时间: 2023-05-21 21:01:48 浏览: 146
一个表的增删改查功能的实现
4星 · 用户满意度95%
好的,以下是一个简单的可变数组的线性表的 C 语言实现,包含数据的增删改查功能:
```c
#include <stdio.h>
#include <stdlib.h>
#define INIT_CAPACITY 10
typedef struct {
int *data;
int size;
int capacity;
} ArrayList;
void init(ArrayList *list) {
list->data = (int *) malloc(INIT_CAPACITY * sizeof(int));
list->size = 0;
list->capacity = INIT_CAPACITY;
}
void resize(ArrayList *list) {
list->capacity *= 2;
list->data = (int *) realloc(list->data, list->capacity * sizeof(int));
}
void add(ArrayList *list, int value) {
if (list->size == list->capacity) {
resize(list);
}
list->data[list->size++] = value;
}
int get(ArrayList *list, int index) {
if (index < 0 || index >= list->size) {
printf("Index out of bounds\n");
return -1;
}
return list->data[index];
}
void set(ArrayList *list, int index, int value) {
if (index < 0 || index >= list->size) {
printf("Index out of bounds\n");
return;
}
list->data[index] = value;
}
void removeAt(ArrayList *list, int index) {
if (index < 0 || index >= list->size) {
printf("Index out of bounds\n");
return;
}
for (int i = index; i < list->size - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->size--;
}
int indexOf(ArrayList *list, int value) {
for (int i = 0; i < list->size; i++) {
if (list->data[i] == value) {
return i;
}
}
return -1;
}
int main() {
ArrayList list;
init(&list);
add(&list, 1);
add(&list, 2);
add(&list, 3);
printf("List size: %d\n", list.size);
printf("List capacity: %d\n", list.capacity);
printf("Element at index 1: %d\n", get(&list, 1));
set(&list, 1, 4);
printf("Element at index 1 after set: %d\n", get(&list, 1));
removeAt(&list, 0);
printf("List size after remove: %d\n", list.size);
printf("Element at index 0 after remove: %d\n", get(&list, 0));
printf("Index of value 3: %d\n", indexOf(&list, 3));
printf("Index of value 5: %d\n", indexOf(&list, 5));
free(list.data);
return 0;
}
```
这个实现使用了动态数组,即在数组满时自动扩容。在初始化时,我们分配了一个初始容量为 10 的数组。当数组满时,我们使用 `realloc` 函数将数组的容量加倍。在添加元素时,如果数组已满,我们调用 `resize` 函数来扩容。在获取、设置和删除元素时,我们检查索引是否越界。在查找元素的索引时,我们遍历整个数组并比较每个元素的值。
阅读全文