#include<iostream>
#define max 10
typedef int abc;
using namespace std;
struct lian {
abc date[max];
int length;
};
class lei {
public:
void creat(lian*& l, abc a[], int n) {//创建一个顺序线性表
int i;
int k = 0;
l = (lian*)malloc(sizeof(lian));
for (i = 0; i < n; i++) {
l->date[i] = a[i];
k++;
}
l->length = k;
}
void initlian(lian*& l) {//初始化一个空顺序线性表
l = (lian*)malloc(sizeof(lian));
l->length = 0;
}
bool empty(lian* l) {//判断一个顺序线性表是否为空
return(l->length == 0);
}
bool full(lian* l) {
return(l->length == max + 1);
}
bool chazhao(lian* l, int i, abc& e) {//查找顺序线性表的第i个元素
if (i<1 || i>l->length) {
cout << "查找超出范围" << endl;
}
e = l->date[i - 1];
cout << "第" << i << "个元素是" << e << endl;
return true;
}
bool locate(lian* l, abc e) {//判断给定的数在该顺序线性表的第几个位置或者不在
int i = 0;
while (i < l->length&& l->date[i] != e) {
i++;
}
if (l->date[i] == e) {
cout << "元素" << e << "位于该表的第" << i + 1 << "个位置" << endl;
return true;
}
else {
cout << "在该表中找不到元素" << e << endl;
return false;
}
}
bool insert(lian* l, int i, abc e) {//将某一个数值插入到顺序线性表的一个位置
if (i<1 || i>l->length + 1) {
cout << "插入错误" << endl;
return false;
}
int j;
for (j = l->length; j > i - 1; j--) {
l->date[j] = l->date[j - 1];
}
l->date[j] = e;
l->length++;
cout << "已经将" << e << "插入到第" << i << "个元素" << endl;
display(l);
}
bool deletel(lian* l, int i, abc& e) {//将线性顺序表的某一个元素删除
if (i<1 || i>l->length) {
cout << "删除错误" << endl;
return false;
}
e = l->date[i - 1];
int j;
for (j = i - 1; j < l->length; j++) {
l->date[j] = l->date[j + 1];
}
l->length--;
cout << "已将第" << i << "个元素" << e << "删除" << endl;
display(l);
}
void display(lian* l) {//输出当前最新的顺序线性表的元素
int i;
cout << "最新的表的数据为:";
for (i = 0; i < l->length; i++) {
cout << l->date[i] << " ";
}
cout << endl;
}
void distory(lian* l) {//释放线性表的空间
free(l);
}
};
int main() {//对所编写的函数进行实例化的测试
int m;
lei text1;
int a[5] = { 1,2,3,4,5 };
lian* p;
text1.creat(p, a, 5);
text1.display(p);
text1.insert(p, 3, 9);
if (text1.empty(p) == 1) {
cout << "该表为空" << endl;
}
else {
cout << "该表不为空" << endl;
}
if (text1.full(p) == 1) {
cout << "该表满了" << endl;
}
else {
cout << "该表不满" << endl;
}
text1.deletel(p, 1, m);
text1.locate(p, 2 );
text1.chazhao(p, 2, m);
text1.distory(p);
}
线性顺序表相关的函数及对函数的调用实例化
最新推荐文章于 2022-10-24 17:07:53 发布