帮我用c语言创建一个数组线性表
时间: 2023-05-12 14:07:18 浏览: 110
C语言实现线性表
当然可以,以下是一个简单的示例代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int length;
} SeqList;
void initList(SeqList *list) {
list->length = 0;
}
void insert(SeqList *list, int index, int value) {
if (list->length >= MAX_SIZE) {
printf("Error: List is full\n");
return;
}
if (index < 0 || index > list->length) {
printf("Error: Invalid index\n");
return;
}
for (int i = list->length; i > index; i--) {
list->data[i] = list->data[i-1];
}
list->data[index] = value;
list->length++;
}
void delete(SeqList *list, int index) {
if (index < 0 || index >= list->length) {
printf("Error: Invalid index\n");
return;
}
for (int i = index; i < list->length-1; i++) {
list->data[i] = list->data[i+1];
}
list->length--;
}
int main() {
SeqList list;
initList(&list);
insert(&list, 0, 1);
insert(&list, 1, 2);
insert(&list, 2, 3);
delete(&list, 1);
for (int i = 0; i < list.length; i++) {
printf("%d ", list.data[i]);
}
printf("\n");
return 0;
}
阅读全文