通过结构体将数组封装为线性表,用c语言实现实现插入、删除、获取、修改、输出等操作。
时间: 2023-12-21 16:03:13 浏览: 26
下面是一个示例代码,实现了结构体封装的线性表的基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE]; // 存储数据的数组
int length; // 线性表的长度
} List;
// 初始化线性表
void initList(List *list) {
list->length = 0;
}
// 打印线性表
void printList(List list) {
int i;
printf("List: ");
for (i = 0; i < list.length; i++) {
printf("%d ", list.data[i]);
}
printf("\n");
}
// 获取元素
int get(List list, int index) {
if (index < 0 || index >= list.length) {
printf("Index out of range.\n");
return -1;
}
return list.data[index];
}
// 插入元素
void insert(List *list, int index, int value) {
if (index < 0 || index > list->length) {
printf("Index out of range.\n");
return;
}
if (list->length >= MAX_SIZE) {
printf("List is full.\n");
return;
}
int i;
for (i = list->length - 1; i >= index; i--) {
list->data[i+1] = list->data[i];
}
list->data[index] = value;
list->length++;
}
// 删除元素
void remove(List *list, int index) {
if (index < 0 || index >= list->length) {
printf("Index out of range.\n");
return;
}
int i;
for (i = index; i < list->length - 1; i++) {
list->data[i] = list->data[i+1];
}
list->length--;
}
// 修改元素
void set(List *list, int index, int value) {
if (index < 0 || index >= list->length) {
printf("Index out of range.\n");
return;
}
list->data[index] = value;
}
int main() {
List list;
initList(&list);
insert(&list, 0, 1);
insert(&list, 1, 2);
insert(&list, 2, 3);
printList(list); // List: 1 2 3
remove(&list, 1);
printList(list); // List: 1 3
set(&list, 1, 4);
printList(list); // List: 1 4
printf("Element at index 1: %d\n", get(list, 1)); // Element at index 1: 4
return 0;
}
```
在这个示例代码中,使用结构体封装了一个数组,其中 `length` 表示线性表的长度。然后实现了初始化、打印、获取、插入、删除、修改等操作。在 `main` 函数中进行了测试。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)