实验一顺序表的实现

#include<iostream>
using namespace std;
const int MaxSize=100;
template <class DataType>
class SeqList
{
	public:
		SeqList(){length=0;}
		SeqList(DataType a[],int n);
		~SeqList(){}
		int Length(){return length;}
		DataType Number(int i);//查找第i个元素
		int Locate(DataType x);//查找值为x的元素序号
		void Add(int i,DataType x);//在第i个位置插入值为x的元素
		DataType Delete(int i);//删除操作
		void Show();//遍历操作
	private:
		DataType data[MaxSize];
		int length;//线性表的长度
};
template<class DataType>
SeqList<DataType>::SeqList(DataType a[],int n)
{
	if(n>MaxSize)
		cout<<"参数非法"<<endl;
	for(i=0;i<=n;i++)
		data[i]=a[i];
	length=n;
}
template<class DataType>
DataType SeqList<DataType>::Number(int i)
{
	if(i<1&&i>length)
		cout<<"查找位置非法"<<endl;
	else return data[i-1];
}
template<class DataType>
int SeqList<DataType>::Locate(DataType x)
{
	for(i=0;i<length;i++)
		if(data[i]==x)
			return i+1;
		return 0;
}
template<class DataType>
void SeqList<DataType>::Add(int i,DataType x)
{
	if(length>=MaxSize)
		cout<<"上溢"<<endl;
	if(i<1||i>length+1)
		cout<<"位置"<<endl;
	for(j=length;j>=1;j--)
		data[j]=data[j-1];
	data[i-1]=x;
	length++;
}
template<class DataType>
DataType SeqList<DataType>::Delete(int i)
{
	if(length==0)
		cout<<"上溢"<<endl;
	if(i<1||i>length)
		cout<<"位置"<<endl;
	x=data[i-1];
	for(j=1;j<length;j++)
		data[j-1]=data[j];
	length--;
	return x;
}
template<class DataType>
void SeqList<DataType>::Show()
{
	for(i=0;i<length;i++)
		cout<<data[i];
}
void main()
{
	int a[5]={100,90,80,70,60};
	SeqList<int> student(a,5);
	cout<<"学生成绩如下所示"<<endl;
	student.Show();
	cout<<"在第二个位置插入数据85"<<endl;
	student.Add(2,85);
	student.Show();
	cout<<"删除第四个位置的成绩为"<<student.Delete(4)<<endl;
	cout<<"第五个成绩为"<<student.Number(5)<<endl;
	cout<<"成绩为100的所在位置为"<<student.Locate(100)<<endl;
}



猜你喜欢

转载自blog.csdn.net/Sing___546/article/details/78079655