下面是结合C++类模板,给出的线性表顺序存储结构实现的实例,刚入门C++不久,程序中如有bug还望大家多多指教!
//线性表顺序存储结构实现
#include "stdio.h"
#include "iostream"
using namespace std;
const int MAXSIZE = 100;
template<class T>
class SqList
{
public:
SqList(); //无参构造函数
SqList(T a[], int n); //带参数构造函数
SqList(int n);
~SqList(){} //析构函数
int LengthSqList(); //返回线性表的长度
void OutPutSqList(); //输出线性表
int EmptySqList(); //线性表已存在的条件下,判断是否为空表
void LocateSqList(T x); //输出数据元素x的位置信息
T GetElemSqList(int i); //获取i位置的元素值
void InsertSqList(int i, T x); //在表i位置插入数据x
int DeleteSqList1(T x); //删除数据元素x
T DeleteSqList2(int i);
private:
T data[MAXSIZE];
int length;
};
template<class T>
SqList<T>::SqList(T a[], int n)
{
if (n > MAXSIZE)
throw "输入的n参数非法";
for(int i = 0; i < n; i++)
data[i] = a[i];
length = n;
cout << "初始化完成..." << endl;
}
template<class T>
SqList<T>::SqList(int n)
{
if(n > MAXSIZE)
throw "输入的n参数非法";
cout << "按照元素个数输入元素值(各元素以空格键隔开):" << endl;
for(int i = 0;i < n; i++)
cin >> data[i];
length = n;
cout << "初始化完成..." << endl;
}
template<class T>
int SqList<T>::LengthSqList()
{
return length;
}
template<class T>
int SqList<T>::EmptySqList()
{
if(length == 0)
return 0;
else
return 1;
}
template<class T>
void SqList<T>::LocateSqList(T x)
{
if(!EmptySqList())
{
cout << "空表,无法进行查询!" << endl;
}
else
{
for (int i = 0; i < length; i++)
{
if(data[i] == x)
cout << i + 1 << endl;
}
cout << "没有找到" << x << "元素!" << endl;
}
}
template<class T>
T SqList<T>::GetElemSqList(int i)
{
T Elem;
if (!EmptySqList())
{
cout << "空表,无法进行查询!" << endl;
}
if (i < 0 && i > MAXSIZE)
throw "输入i参数非法";
else
{
Elem = data[i-1];
return Elem;
}
}
template<class T>
void SqList<T>::InsertSqList(int i, T x)
{
if(!EmptySqList())
throw "空表,无法进行插入";
if (i < 1 && i > MAXSIZE)
throw "输入i参数非法";
else
{
for(int j = length - 1; j >= i - 1; j--)
data[j + 1] = data[j];
data[i - 1] = x;
length++;
}
}
template<class T>
int SqList<T>::DeleteSqList1(T x)
{
if(!EmptySqList())
throw "空表,无法进行插入";
else
{
int n;
for (int i = 0; i < length; i++)
{
if(data[i] == x)
n = i;
}
for (int j = n; j < length; j++)
{
data[j] = data[j + 1];
}
length--;
return n;
}
}
template<class T>
T SqList<T>::DeleteSqList2(int i)
{
if(!EmptySqList())
throw "空表,无法进行插入";
else
{
T Elem = data[i - 1];
for(int j = i - 1; j < length; j++)
data[j] = data[j+1];
length--;
return Elem;
}
}
template<class T>
void SqList<T>::OutPutSqList()
{
cout << "线性表内容为:" << endl;
for (int i = 0; i< length; i++)
cout << data[i] << " ";
cout << endl;
}
int main()
{
int arry[] = {1, 2, 3, 2, 5};
int i = 5;
SqList<int> sqlist1(arry, i);
sqlist1.OutPutSqList();
cout << "线性表的长度是:" << sqlist1.LengthSqList() << endl;
cout << "元素2在线性表的位置是:" << endl;
sqlist1.LocateSqList(2);
cout << "线性表中位置为2的元素是:" << sqlist1.GetElemSqList(2) << endl;
cout << "删除元素4" << endl;
sqlist1.DeleteSqList1(2);
sqlist1.OutPutSqList();
cout << "在位置2上添加元素110" << endl;
sqlist1.InsertSqList(2, 110);
sqlist1.OutPutSqList();
return 0;
}
测序测试结果图: