数据结构C语言实现顺序表的插入
时间: 2023-10-03 19:07:21 浏览: 112
顺序表的插入操作需要考虑两个方面:插入位置和移动元素。具体代码如下:
```c
#include <stdio.h>
#define MAXSIZE 100 // 定义最大长度
typedef struct {
int data[MAXSIZE]; // 数组存储数据元素
int length; // 顺序表当前长度
} SqList;
// 插入操作
int insert(SqList *L, int pos, int e) {
// 判断插入位置是否合法
if (pos < 1 || pos > L->length + 1) {
return 0;
}
// 如果顺序表已满,无法插入
if (L->length == MAXSIZE) {
return 0;
}
// 将 pos 后面的元素依次向后移动一位
for (int i = L->length; i >= pos; i--) {
L->data[i] = L->data[i-1];
}
// 插入元素 e
L->data[pos-1] = e;
L->length++; // 长度加 1
return 1;
}
int main() {
SqList L = {{1, 2, 3, 4}, 4}; // 初始化顺序表
int pos, e;
printf("请输入插入位置和插入元素,用空格分隔:");
scanf("%d %d", &pos, &e);
int result = insert(&L, pos, e); // 插入操作
if (result) { // 判断插入是否成功
printf("插入后的顺序表为:");
for (int i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
} else {
printf("插入失败!\n");
}
return 0;
}
```
以上代码中,`SqList` 结构体表示顺序表,其中 `data` 数组存储数据元素,`length` 表示当前顺序表长度。`insert` 函数实现了在顺序表 `L` 的第 `pos` 个位置插入元素 `e` 的操作。如果插入位置不合法或者顺序表已满,函数返回 0,插入成功返回 1。在主函数中,用户输入插入位置和插入元素,然后调用 `insert` 函数进行插入操作,并输出插入后的顺序表。
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)