题目描述
【问题描述】查找顺序表第i个位置(逻辑位序)插入新元素e。若插入位置不合法,则返回false,输出“The insertion position does not exist”和顺序表的表长。成功则输出插入后的新表。假设顺序表的元素为整型数据。
【输入形式】第1行顺序表的长度;第2行顺序表各数据元素;第3行为插入位置和插入元素。
【输出形式】若顺序表插入成功,则先输出插入后的顺序表,插入失败则输出“The insertion position does not exist”和顺序表的表长。
【样例输入】
10
8 19 96 38 83 47 67 72 93 82
5 20
【样例输出】
8 19 96 38 20 83 47 67 72 93 82
【样例输入】
8
19 30 90 92 0 95 20 51
15 30
【样例输出】
The insertion position does not exist
8
解题思路
根据题意写出实现顺序表的框架代码,判断删除索引是否合理并进行插入返回0/1代表插入是否合法,将顺序表插入索引处后移并插入值
源代码
#include <iostream>
#include <stdlib.h>
using namespace std;
#define MaxSize 100
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int length;
} SqList;
void InitList(SqList& L) { //初始化顺序表
//L = (SqList*)malloc(sizeof(SqList));
L.length = 0;
}
int InsElem(SqList& L, int i, int e) { //按索引插入
if (i<1 || i>L.length)
return 0;
int j;
for (j = L.length; j > i - 1; j--)
L.data[j] = L.data[j - 1];
L.data[i - 1] = e;
L.length++;
return 1;
}
void PrintElem(SqList L) { //输出顺序表
int i;
for (i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
}
int main() {
int n, i, e;
SqList L;
InitList(L);
cin >> n;
for (i = 0; i < n; i++) {
cin >> L.data[i];
L.length++;
}
cin >> i;
cin >> e;
if (InsElem(L, i, e)) {
PrintElem(L);
}
else {
cout << "The insertion position does not exist" << endl;
cout << L.length << endl;
}
system("pause");
return 0;
}
总结
顺序表的简单应用~