数据结构-线性表-顺序表
#include <iostream>
using namespace std;
int maxSize = 100;
typedef int ElemType;
struct seqList{
ElemType *arr;
int length;
};
typedef struct seqList SeqList;
bool inItSeqList(SeqList &L)
{
L.arr = new ElemType[maxSize];
if (!L.arr) {
return false;
}
L.length = 0;
return true;
}
bool createSeqList(SeqList &L) {
int x, i = 0;
while (1) {
if (L.length == maxSize) {
cout << "顺序表已经存储满了";
return true;
}
cin >> x;
if (x == -1) {
cout << "输入结束";
return true;
}
L.arr[i++] = x;
L.length++;
}
}
bool getElement(SeqList &L, int i, int &h) {
if (i < 0 || i >= L.length) {
cout << "i的范围超出" << endl;
return false;
}
h = L.arr[i];
return true;
}
bool selectValue(SeqList &L, int h) {
for (int i = 0; i < L.length; i++) {
if (h == L.arr[i]) {
return true;
}
}
return false;
}
bool insertValue(SeqList &L, int i, int h) {
if (i < 0 || i > L.length) {
cout << "i超出范围";
return false;
}
if (L.length == maxSize) {
return false;
}
for (int j = L.length - 1; j >= i; j--) {
L.arr[j + 1] = L.arr[j];
}
L.arr[i] = h;
L.length++;
return true;
}
bool deleteValue(SeqList &L, int i) {
if (i < 0 || i > L.length - 1) {
cout << "i超出范围";
return false;
}
for (int j = i + 1; j <= L.length - 1; j++) {
L.arr[j - 1] = L.arr[j];
}
L.length--;
return true;
}
void traverse(SeqList &L) {
for (int i = 0; i < L.length; i++) {
cout << L.arr[i] << " ";
}
cout << endl;
}
int main() {
SeqList l;
if (inItSeqList(l)) {
cout << "初始化成功" << endl;
}
if (createSeqList(l)) {
cout << "创建顺序表成功" << endl;
}
traverse(l);
int e;
if (getElement(l, 2, e)) {
cout << "取出的值为" << e << endl;
}
if (selectValue(l, 10)) {
cout << "找到该值" << endl;
} else {
cout << "没找到该值" << endl;
}
if (insertValue(l, 1, 10)) {
cout << "插入成功" << endl;
} else {
cout << "插入失败" << endl;
}
traverse(l);
if (deleteValue(l, 1)) {
cout << "删除成功" << endl;
} else {
cout << "删除失败" << endl;
}
traverse(l);
return 0;
}