静态分配顺序存储结构的线性表:
头文件:
#include<iostream>
const int MAXSIZE = 100;
template<class DataType>
class SqList {
public:
SqList() { length = 0 }
SqList(DataType array[], int n);
~SqList() {}
int GetLength() { return length; }//获取顺序表长度
DataType GetElement(int i);//获取位置所在的元素
int GetLocal(DataType x);//获取元素所在位置
void Insert(int i, DataType x);//顺序表插入元素
DataType Delete(int i);//顺序表删除元素
void PrintSqList();
private:
DataType data[MAXSIZE];//一维数组
int length;//顺序表长度
};
template<class DataType>
SqList<DataType>::SqList(DataType array[], int n)
{
if (n > MAXSIZE)
{
throw"传入的顺序表长度过长";
}
for (int i = 0; i < n; i++)
{
data[i] = array[i];
}
length = n;
}
template<class DataType>
DataType SqList<DataType>::GetElement(int i)
{
if (i<1 || i>length)
{
throw"位置输入有误";
}
else
{
return data[i-1];
}
}
template<class DataType>
int SqList<DataType>::GetLocal(DataType x)
{
for (int i = 0; i < length; i++)
{
if (data[i] == x)
{
return (i + 1);
}
}
return 0;
}
template<class DataType>
void SqList<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<class DataType>
DataType SqList<DataType>::Delete(int index)
{
DataType x;
if (index<1 || index>length)
{
throw "删除位置有误";
}
else
{
x = data[index - 1];
for (int i = index; i < length; i++)
{
data[i - 1] = data[i];
}
length--;
}
return x;
}
template<class DataType>
void SqList<DataType>::PrintSqList()
{
if (length < 1)
{
throw "无元素";
}
else
{
for (int i = 0; i < length; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
}
源文件:
#include<iostream>
#include"SqList.h"
using namespace std;
void show()
{
cout << "------------------------------------" << endl;
}
int main()
{
int array[10] = { 1,2,3,4,5,6,7,8,9,14 };
SqList<int> list =SqList<int>(array, 10);
cout << "顺序表:" << endl;
list.PrintSqList();
show();
cout << "长度:" << list.GetLength() << endl;
cout << "第五个元素:" << list.GetElement(5) << endl;
cout << "元素8的位置" << list.GetLocal(8) << endl;
show();
cout << "第1个位置插入40" << endl;
list.Insert(1, 40);
cout << "顺序表为:" << endl;
list.PrintSqList();
cout << "长度:" << list.GetLength() << endl;
cout << "删除第7个元素" << endl;
list.Delete(7);
cout << "顺序表:" << endl;
list.PrintSqList();
cout << "顺序表长度:" << list.GetLength() << endl;
show();
system("pause");
return 0;
}