编写应用程序,实现可以在顺序表中插入任意给定数据类型数据的功能(定义为ElemType抽象数据类型)。要求在主函数中定义顺序表并对该顺序表插入若干个整数类型的数据(正整数),对它们求和并输出。
SqList.h
#include<iostream>
using namespace std;
typedef int ElemType;
#define MAXSize 50
#define OVERFLOW -2
typedef struct List {
ElemType* elem;
int length;
}SqList;
void InitList(SqList& L)
{
//构造一个空的顺序表
L.elem = new ElemType[MAXSize];
if (!L.elem) exit(OVERFLOW);
L.length = 0;
cout << "初始化成功..."<<endl;
}
void ClearList(SqList& L)
{
//清空线性表,不销毁
L.length = 0;
}
int ListLength(SqList L)
{
return L.length;
}
bool ListInsert(SqList& L, int i, ElemType e)
{
//在线性表L中第i个数据元素之前插入新数据元素e
if (i<1 || i>L.length + 1)
return false; //插入位置不合法
if (L.length >= MAXSize)
return false;
for (int j = L.length; j >= i; j--)
{
L.elem[j] = L.elem[j - 1];
}
L.elem[i - 1] = e;
L.length++;
return true;
}
ElemType GetElem(SqList L, int i)
{
//在线性表L中求序号为i的元素,该元素作为函数的返回值
if (i<1 || i>L.length)
{
cout << "i不在[1...n]范围内";
exit(OVERFLOW);
}
return L.elem[i - 1];
}
SqList.cpp
#include "SqList.h"
int main()
{
SqList L;
InitList(L);//???为什么不是&L
//向线性表中插入数据
int i = 1, e, n,q=-1,sum=0;
cin >> e;
while (e!=666)
{
if (!ListInsert(L, i, e))
{
cout << "插入错误!";
return 0;
}
i++;
cin >> e;
}
//查找序号为q的元素
cout << "请输入要查找的数据序号: ";
cin >> q;
while (q!=777)
{
cout << GetElem(L, q) << endl;
cout << "请输入要查找的数据序号: ";
cin >> q;
}
//输入线性表长度
n = ListLength(L);
//求线性表数据元素的和
for (int i = 1; i <= n; i++)
{
e = GetElem(L, i);
sum += e;
}
cout << "线性表数据元素的和为:"<<sum << endl;
ClearList(L);
}