写一个c语言顺序表代码
时间: 2023-04-05 13:02:00 浏览: 103
用C语言实现的顺序表
好的,我可以回答这个问题。以下是一个简单的 C 语言顺序表代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int length;
} SeqList;
void init(SeqList *list) {
list->length = 0;
}
int insert(SeqList *list, int index, int value) {
if (index < 0 || index > list->length || list->length == MAX_SIZE) {
return 0;
}
for (int i = list->length - 1; i >= index; i--) {
list->data[i + 1] = list->data[i];
}
list->data[index] = value;
list->length++;
return 1;
}
int delete(SeqList *list, int index) {
if (index < 0 || index >= list->length) {
return 0;
}
for (int i = index; i < list->length - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->length--;
return 1;
}
int get(SeqList *list, int index) {
if (index < 0 || index >= list->length) {
return -1;
}
return list->data[index];
}
void print(SeqList *list) {
for (int i = 0; i < list->length; i++) {
printf("%d ", list->data[i]);
}
printf("\n");
}
int main() {
SeqList list;
init(&list);
insert(&list, 0, 1);
insert(&list, 1, 2);
insert(&list, 2, 3);
print(&list);
delete(&list, 1);
print(&list);
printf("%d\n", get(&list, 1));
return 0;
}
```
这个代码实现了一个顺序表,可以进行插入、删除、获取元素和打印等操作。
阅读全文