啊啊啊看着就头疼,不想总结了,有时间再来吧。附上前两天的代码。
不懂之处主要如下:
- template类模板的使用
- 析构函数
#include<iostream>
using namespace std;
const int MaxSize = 100;
//定义顺序表SeqList的模板类
template <class datatype>
class SeqList
{
public:
//顺序表无参构造器
SeqList();
//有参构造器
SeqList(datatype arr[], int n);
//析构函数
~SeqList(){}
//求顺序表长度
void GetLength();
//返回i位置元素
datatype GetElemate(int i);
//返回元素位置
int GetLocation(datatype x);
//指定位置插入元素
void Insert(int i, datatype x);
//删除指定位置元素
void Delete(int i, datatype *e);
void PrintSeqList();
private:
datatype data[MaxSize];
int length;
};
template <class datatype>
SeqList<datatype>::SeqList(datatype arr[], int n)
{
if(n > MaxSize)
{
cout<<"输入链表过长"<<endl;
}
for(int i = 0; i < n; i++)
{
data[i] = arr[i];
}
length = n;
}
template <class datatype>
void SeqList<datatype>::GetLength()
{
cout<<"长度为:"<<length<<endl;
}
template <class datatype>
datatype SeqList<datatype>::GetElemate(int i)
{
if(i < 1 || i > length)
{
cout<<"位置有误"<<endl;
}
return data[i-1];
}
template <class datatype>
int SeqList<datatype>::GetLocation(datatype x)
{
for(int j = 1; j <= length; j++)
{
if(data[j-1] == x)
return j;
}
}
template <class datatype>
void SeqList<datatype>::Insert(int i, datatype x)
{
if(i < 1 || i > length)
{
cout<<"输入位置有误"<<endl;
}
if(i == length)
{
data[i] = x;
}
//j为下标
for(int j = length; j > i-1; j--)
{
data[j] = data[j-1];
}
data[i-1] = x;
length++;
}
template <class datatype>
void SeqList<datatype>::Delete(int i, datatype *e)
{
if(i < 1 || i > length)
{
cout<<"删除位置有误"<<endl;
}
*e = data[i-1];
for(int j = i; j < length; j++)
{
data[j-1] = data[j];
}
length--;
}
template <class datatype>
void SeqList<datatype>::PrintSeqList()
{
if(length<1)
{
cout<<"no elemate"<<endl;
}
cout<<"顺序表元素为:"<<endl;
for(int j = 0; j < length; j++)
{
cout<<data[j]<<" ";
}
cout<<endl;
}
int main()
{
int arr[10] = {1,3,4,2,5,6,8,7,9,10};
SeqList<int> sq = SeqList<int>(arr, 10);
sq.PrintSeqList();
sq.GetLength();
int ele = sq.GetElemate(4);
cout<<"ele = " << ele<<endl;
int loc = sq.GetLocation(7);
cout<<"loc = "<<loc<<endl;
int e = 0;
sq.Delete(5, &e);
cout<<"delete ele = "<<e<<endl;
sq.PrintSeqList();
sq.Insert(4, 39);
sq.PrintSeqList();
}
参考链接:https://www.cnblogs.com/zfc-java/p/6659639.html
类模板参考链接:https://blog.csdn.net/lf_2016/article/details/51944729