#include <iostream>
using namespace std;
#define MAXSIZE 100 // 定义顺序表的最大长度
typedef struct {
int data[MAXSIZE]; // 存储顺序表元素
int last; // 记录顺序表最后一个元素的下标
} SqList;
// 初始化顺序表
void InitList(SqList &L) {
L.last = -1; // 初始时,顺序表中没有元素
}
// 插入元素e到顺序表L的第i个位置
bool ListInsert(SqList &L, int i, int e) {
if (i < 1 || i > L.last + 2 || L.last == MAXSIZE - 1) { // 判断插入位置是否合法,以及顺序表是否已满
return false;
}
for (int j = L.last; j >= i - 1; j--) { // 将第i个位置及其后面的元素后移一位
L.data[j + 1] = L.data[j];
}
L.data[i - 1] = e; // 将元素e插入到第i个位置
L.last++; // 顺序表长度加1
return true;
}
// 输出顺序表中的所有元素
void PrintList(SqList L) {
for (int i = 0; i <= L.last; i++) {
cout << L.data[i] << " ";
}
cout << endl;
}
int main() {
SqList L;
InitList(L); // 初始化顺序表
int n, e;
cout << "请输入顺序表的长度:";
cin >> n;
cout << "请输入" << n << "个整数作为顺序表的元素:";
for (int i = 0; i < n; i++) {
cin >> L.data[i];
L.last++; // 顺序表长度加1
}
cout << "顺序表中的元素为:";
PrintList(L); // 输出顺序表中的所有元素
int i;
cout << "请输入要插入的元素和插入位置(用空格隔开):";
cin >> e >> i;
if (ListInsert(L, i, e)) { // 插入元素e到顺序表L的第i个位置
cout << "插入成功!插入后的顺序表为:";
PrintList(L); // 输出插入后的顺序表中的所有元素
} else {
cout << "插入失败!" << endl;
}
return 0;
}