帮我用c语言写一个建立顺序线性表的代码
时间: 2023-03-28 22:01:40 浏览: 113
好的,以下是建立顺序线性表的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 定义线性表的最大长度
typedef struct {
int data[MAXSIZE]; // 存储线性表元素的数组
int length; // 线性表的当前长度
} SqList; // 定义顺序线性表类型
void InitList(SqList *L) { // 初始化线性表
L->length = ; // 将线性表长度初始化为
}
int ListInsert(SqList *L, int i, int e) { // 在第i个位置插入元素e
if (i < 1 || i > L->length + 1) { // 判断i的范围是否合法
return ; // 插入失败,返回
}
if (L->length >= MAXSIZE) { // 判断线性表是否已满
return ; // 插入失败,返回
}
for (int j = L->length; j >= i; j--) { // 将第i个位置及之后的元素后移
L->data[j] = L->data[j - 1];
}
L->data[i - 1] = e; // 将元素e插入到第i个位置
L->length++; // 线性表长度加1
return 1; // 插入成功,返回1
}
void PrintList(SqList L) { // 输出线性表
for (int i = ; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
int main() {
SqList L; // 声明一个顺序线性表
InitList(&L); // 初始化线性表
ListInsert(&L, 1, 1); // 在第1个位置插入元素1
ListInsert(&L, 2, 2); // 在第2个位置插入元素2
ListInsert(&L, 3, 3); // 在第3个位置插入元素3
PrintList(L); // 输出线性表
return ;
}
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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)