编写函数:长度最大为20个整型元素的线性表,插入、删除整数,每插入或删除一次后显示出变化后的线性表,在主函数中调用实现;
时间: 2023-04-14 16:05:19 浏览: 118
好的,下面是函数的代码实现:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 20;
struct List {
int data[MAX_SIZE];
int length;
};
void initList(List &L) {
L.length = ;
}
void displayList(List L) {
for (int i = ; i < L.length; i++) {
cout << L.data[i] << " ";
}
cout << endl;
}
bool insertList(List &L, int pos, int val) {
if (pos < 1 || pos > L.length + 1 || L.length == MAX_SIZE) {
return false;
}
for (int i = L.length - 1; i >= pos - 1; i--) {
L.data[i + 1] = L.data[i];
}
L.data[pos - 1] = val;
L.length++;
return true;
}
bool deleteList(List &L, int pos) {
if (pos < 1 || pos > L.length) {
return false;
}
for (int i = pos; i < L.length; i++) {
L.data[i - 1] = L.data[i];
}
L.length--;
return true;
}
int main() {
List L;
initList(L);
insertList(L, 1, 10);
displayList(L);
insertList(L, 2, 20);
displayList(L);
insertList(L, 1, 30);
displayList(L);
deleteList(L, 2);
displayList(L);
deleteList(L, 1);
displayList(L);
return ;
}
```
在主函数中,我们首先初始化了一个长度为的线性表L,然后依次进行了插入和删除操作,并在每次操作后调用了displayList函数来显示变化后的线性表。
需要注意的是,我们在插入和删除操作中都加入了一些判断,以确保操作的合法性。比如,插入操作时需要判断插入位置是否合法以及线性表是否已满;删除操作时需要判断删除位置是否合法。如果操作不合法,函数会返回false,我们可以根据返回值来判断操作是否成功。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.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)