C++写一个程序,在顺序表中存入若干个元素,并分别编写三个函数,实现如下功能: 在顺序表a的第i个位置插入元素x; 删除第i个位置的元素; 查找指定位置的元素值。
时间: 2023-05-29 20:08:05 浏览: 62
```c
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
} SeqList;
void init(SeqList *L) {
L->length = 0;
}
void insert(SeqList *L, int i, int x) {
if (i < 1 || i > L->length + 1) {
printf("插入位置不合法\n");
return;
}
if (L->length == MAXSIZE) {
printf("顺序表已满\n");
return;
}
for (int j = L->length; j >= i; j--) {
L->data[j] = L->data[j-1];
}
L->data[i-1] = x;
L->length++;
}
void delete(SeqList *L, int i) {
if (i < 1 || i > L->length) {
printf("删除位置不合法\n");
return;
}
for (int j = i; j < L->length; j++) {
L->data[j-1] = L->data[j];
}
L->length--;
}
int get(SeqList *L, int i) {
if (i < 1 || i > L->length) {
printf("查找位置不合法\n");
return -1;
}
return L->data[i-1];
}
int main() {
SeqList L;
init(&L);
insert(&L, 1, 10);
insert(&L, 2, 20);
insert(&L, 3, 30);
printf("顺序表:");
for (int i = 1; i <= L.length; i++) {
printf("%d ", L.data[i-1]);
}
printf("\n");
insert(&L, 2, 40);
printf("顺序表:");
for (int i = 1; i <= L.length; i++) {
printf("%d ", L.data[i-1]);
}
printf("\n");
delete(&L, 2);
printf("顺序表:");
for (int i = 1; i <= L.length; i++) {
printf("%d ", L.data[i-1]);
}
printf("\n");
printf("第2个元素:%d\n", get(&L, 2));
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)