数据结构--顺序表C++(静态分配内存)(模板类实现)
作者:
AmbitionX
,
2022-04-26 17:21:59
,
所有人可见
,
阅读 175
C++
#include <iostream>
using namespace std;
const int MaxSize = 100;
template <typename DataType>
class SeqList
{
public:
SeqList();
SeqList(DataType a[], int n);
int Length();
DataType Get(int i);
int Locate(DataType x);
void Insert(int i, DataType x);
DataType Delete(int i);
bool Empty();
void PrintList();
private:
DataType data[MaxSize];
int length;
};
template <typename DataType>
SeqList<DataType>:: SeqList(DataType a[], int n)
{
if (n > MaxSize) throw "非法参数";
for (int i = 0; i < n; i++) data[i] = a[i];
length = n;
}
template <typename DataType>
int SeqList<DataType>:: Length()
{
return length;
}
template <typename DataType>
DataType SeqList<DataType>:: Get(int i)
{
if (i < 1 || i > length) throw "查找位置非法";
else return data[i - 1];
}
template <typename DataType>
int SeqList<DataType>:: Locate(DataType x)
{
for (int i = 0; i < length; i++)
if (data[i] == x) return i + 1;
return 0;
}
template <typename DataType>
void SeqList<DataType>:: Insert(int i, DataType x)
{
if (length == MaxSize) throw "上溢";
if (i < 1 || i > length + 1) throw "插入位置发生错误";
for (int j = length; j >= i; j--) data[j] = data[j - 1];
data[i - 1] = x;
length ++;
}
template <typename DataType>
DataType SeqList<DataType>:: Delete(int i)
{
DataType x;
if (length == 0) throw "下溢";
if (i < 1 || i > length) throw "删除位置发生错误";
x = data[i - 1];
for (int j = i; j < length; j++)
data[j - 1] = data[j];
length --;
return x;
}
template <typename DataType>
bool SeqList<DataType>:: Empty()
{
if (length == 0) return true;
return false;
}
template <typename DataType>
void SeqList<DataType>:: PrintList()
{
for (int i = 0; i < length; i++) cout << data[i] << "\t";
cout << endl;
}
int main()
{
int b[5] = {1,2,3,4,5};
SeqList<int> L{b, 5};
cout << "当前线性表的数据为: ";
L.PrintList();
try
{
L.Insert(2, 8);
cout << "执行插入操作后的数据为: ";
L.PrintList();
}
catch (char *str)
{
cout << str << endl;
}
cout << "当前线性表的长度为: " << L.Length() << endl;
int x;
cout << "请输入查找的元素值: ";
cin >> x;
if (L.Locate(x) == 0) cout << "查找失败" << endl;
else cout << "元素" << x << ".位置为: " << L.Locate(x) << endl;
int i;
try
{
cout << "请输入查找第几个元素值: ";
cin >> i;
cout << "第" << i << "个元素值是" << L.Get(i) << endl;
}
catch (char *str)
{
cout << str << endl;
}
int j;
try
{
cout << "请输入要删除第几个元素: ";
cin >> j;
x = L.Delete(j);
cout << "删除的元素是" << x << ",删除后的数据为: ";
L.PrintList();
}
catch (char *str)
{
cout << str << endl;
}
return 0;
}