C语言版顺序表,内存为动态申请
时间: 2024-04-16 11:26:38 浏览: 75
C语言顺序表
5星 · 资源好评率100%
您好!以下是一个简单的C语言版顺序表的示例代码,其中内存动态申请:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int* array;
int length;
int capacity;
} SeqList;
SeqList* createSeqList(int capacity) {
SeqList* list = (SeqList*)malloc(sizeof(SeqList));
if (list == NULL) {
printf("Failed to allocate memory!\n");
return NULL;
}
list->array = (int*)malloc(capacity * sizeof(int));
if (list->array == NULL) {
printf("Failed to allocate memory!\n");
free(list);
return NULL;
}
list->length = 0;
list->capacity = capacity;
return list;
}
void destroySeqList(SeqList* list) {
if (list == NULL) {
return;
}
free(list->array);
free(list);
}
void insert(SeqList* list, int index, int value) {
if (list == NULL || index < 0 || index > list->length) {
printf("Invalid parameters!\n");
return;
}
if (list->length >= list->capacity) {
printf("SeqList is full, cannot insert!\n");
return;
}
for (int i = list->length - 1; i >= index; i--) {
list->array[i + 1] = list->array[i];
}
list->array[index] = value;
list->length++;
}
void remove(SeqList* list, int index) {
if (list == NULL || index < 0 || index >= list->length) {
printf("Invalid parameters!\n");
return;
}
for (int i = index; i < list->length - 1; i++) {
list->array[i] = list->array[i + 1];
}
list->length--;
}
void printSeqList(SeqList* list) {
if (list == NULL) {
printf("Invalid SeqList!\n");
return;
}
printf("SeqList: ");
for (int i = 0; i < list->length; i++) {
printf("%d ", list->array[i]);
}
printf("\n");
}
int main() {
SeqList* list = createSeqList(5);
insert(list, 0, 1);
insert(list, 1, 2);
insert(list, 2, 3);
printSeqList(list);
remove(list, 1);
printSeqList(list);
destroySeqList(list);
return 0;
}
```
这个示例代码实现了一个简单的顺序表,其中内存是通过动态申请的。使用`createSeqList`函数创建顺序表,并指定容量。通过`insert`函数插入元素,`remove`函数删除元素,`printSeqList`函数打印顺序表的内容。最后,使用`destroySeqList`函数销毁顺序表,并释放动态申请的内存。
请注意,这只是一个简单的示例,实际应用中可能需要考虑更多的边界情况和错误处理。
阅读全文