题目描述
【问题描述】删除顺序表第i个位置(逻辑位序)的元素。若删除位置不合法,则返回false,输出“The delete location does not exist”和顺序表的表长。成功则输出删除后的新表和被删除元素。假设顺序表的元素为整型数据。
【输入形式】第1行顺序表的长度;第2行顺序表各数据元素;第3行为删除位置。
【输出形式】若顺序表删除成功,则先输出删除后的顺序表和被删除元素,删除失败则输出“The delete location does not exist”和顺序表的表长。
【样例输入】
10
73 18 12 59 40 45 3 69 7 3
5
【样例输出】
73 18 12 59 45 3 69 7 3
40
【样例输入】
12
6 43 17 17 50 55 93 99 53 92 89 56
15
【样例输出】
The delete location does not exist
12
解题思路
遍历到删除索引,将后面的元素从后往前移
源代码
#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 Deletex(SqList&L, ElemType i,int &e) {
if (i<1 || i>L.length)
return 0;
int j, k = 0;
e = L.data[i-1];
for (j = 0; j < L.length; j++) {
if (j != i-1) {
L.data[k] = L.data[j];
k++;
}
}
L.length = k;
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;
if (Deletex(L, i,e)) {
PrintElem(L);
cout << e << endl;
}
else {
cout << "The delete location does not exist" << endl;
cout << L.length << endl;
}
system("pause");
return 0;
}
总结
较简单的题~