编写从顺序表头部插入数据的函数:void head_insert(SeqList *L, ElemType x); 编写在顺序表的任意位置插入元素的函数
时间: 2024-05-27 15:12:07 浏览: 12
:void insert(SeqList *L, int pos, ElemType x);
其中,SeqList为顺序表类型,ElemType为元素类型,x为要插入的元素,pos为要插入的位置,从0开始计数。具体实现如下:
void head_insert(SeqList *L, ElemType x) {
int i;
if (L->length == MAXSIZE) { // 判断顺序表是否已满
printf("List is full.\n");
return;
}
for (i = L->length; i > 0; i--) { // 将所有元素后移一位
L->data[i] = L->data[i - 1];
}
L->data[0] = x; // 将新元素插入到表头
L->length++; // 表长加1
}
void insert(SeqList *L, int pos, ElemType x) {
int i;
if (pos < 0 || pos > L->length) { // 判断插入位置是否合法
printf("Invalid position.\n");
return;
}
if (L->length == MAXSIZE) { // 判断顺序表是否已满
printf("List is full.\n");
return;
}
for (i = L->length - 1; i >= pos; i--) { // 将pos及其之后的元素后移一位
L->data[i + 1] = L->data[i];
}
L->data[pos] = x; // 将新元素插入到pos位置
L->length++; // 表长加1
}
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)