c语言中用数组定义一个抽象数据类型的list的代码
时间: 2024-04-30 10:23:43 浏览: 103
以下是用数组定义一个抽象数据类型的list的C语言代码示例:
```c
#define MAX_SIZE 100 // 定义最大容量为100
// 定义list结构体
typedef struct {
int data[MAX_SIZE];
int length;
} List;
// 初始化list
void init(List *list) {
list->length = 0;
}
// 判断list是否为空
int isEmpty(List *list) {
return list->length == 0;
}
// 判断list是否已满
int isFull(List *list) {
return list->length == MAX_SIZE;
}
// 在list末尾插入元素
void append(List *list, int value) {
if (isFull(list)) {
printf("List is full.\n");
return;
}
list->data[list->length++] = value;
}
// 在list指定位置插入元素
void insert(List *list, int value, int index) {
if (isFull(list)) {
printf("List is full.\n");
return;
}
if (index < 0 || index > list->length) {
printf("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++;
}
// 删除list指定位置的元素
void delete(List *list, int index) {
if (isEmpty(list)) {
printf("List is empty.\n");
return;
}
if (index < 0 || index >= list->length) {
printf("Invalid index.\n");
return;
}
for (int i = index; i < list->length - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->length--;
}
// 获取list指定位置的元素
int get(List *list, int index) {
if (isEmpty(list)) {
printf("List is empty.\n");
return -1;
}
if (index < 0 || index >= list->length) {
printf("Invalid index.\n");
return -1;
}
return list->data[index];
}
// 修改list指定位置的元素
void set(List *list, int value, int index) {
if (isEmpty(list)) {
printf("List is empty.\n");
return;
}
if (index < 0 || index >= list->length) {
printf("Invalid index.\n");
return;
}
list->data[index] = value;
}
// 打印list中的元素
void print(List *list) {
if (isEmpty(list)) {
printf("List is empty.\n");
return;
}
printf("List: ");
for (int i = 0; i < list->length; i++) {
printf("%d ", list->data[i]);
}
printf("\n");
}
int main() {
List list;
init(&list);
append(&list, 1);
append(&list, 2);
insert(&list, 3, 1);
print(&list); // 输出:List: 1 3 2
delete(&list, 0);
set(&list, 4, 1);
print(&list); // 输出:List: 3 4
return 0;
}
```
阅读全文