用c++建立一个长度为七的线性表
时间: 2024-05-12 20:20:01 浏览: 19
以下是用C语言建立一个长度为七的线性表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 7
typedef struct {
int data[MAX_SIZE];
int length;
} SeqList;
void initList(SeqList *L) {
L->length = 0;
}
void insert(SeqList *L, int index, int value) {
if (L->length >= MAX_SIZE) {
printf("Error: list is full.\n");
return;
}
if (index < 0 || index > L->length) {
printf("Error: index is out of range.\n");
return;
}
for (int i = L->length - 1; i >= index; i--) {
L->data[i + 1] = L->data[i];
}
L->data[index] = value;
L->length++;
}
void printList(SeqList L) {
printf("List:");
for (int i = 0; i < L.length; i++) {
printf(" %d", L.data[i]);
}
printf("\n");
}
int main() {
SeqList L;
initList(&L);
insert(&L, 0, 1);
insert(&L, 1, 2);
insert(&L, 2, 3);
insert(&L, 3, 4);
insert(&L, 4, 5);
insert(&L, 5, 6);
insert(&L, 6, 7);
printList(L);
return 0;
}
```
该代码中,定义了一个结构体`SeqList`,包含一个数组`data`和一个长度`length`,用于表示线性表。`initList`函数用于初始化线性表,将`length`设为0。`insert`函数用于在指定位置插入元素,并根据情况输出错误信息。`printList`函数用于打印整个线性表。在`main`函数中,通过多次调用`insert`函数,向线性表中插入7个元素,并通过`printList`函数打印整个线性表。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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_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)