实验三:用顺序表实现学生系统的基本操作

实验目的:巩固线性表的数据的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。

实验内容:建立一个由n个学生成绩的线性表,n的大小由自己确定,每个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。

源代码:

# ifndef SeqList_H

# define SeqList_H

const int MaxSize=20;

template <class DataType>

class SeqList

{

public:

SeqList(){length=0;}

~SeqList(){}

SeqList(DataType a[],int n);

int Length(){return length;}

DataType Get(int i);

int Locate(DataType x);

void Insert(int i,DataType x);

DataType Delete(int i);

void PrintList();

private:

DataType data[MaxSize];

int length;

};

# endif

# include"SeqList.h"

# include<iostream>

using namespace std;

template<class DataType>

SeqList<DataType>::SeqList(DataType a[],int n)

{

DataType i;

if(n>MaxSize) throw"上溢";

for(i=0;i<n;i++)

data[i]=a[i];

length=n;

}

template<class DataType>

DataType SeqList<DataType>::Get(int i)

{

if(i<1&&i>length) throw"查找位置非法";

else return data[i-1];

}

template<class DataType>

int SeqList<DataType>::Locate(DataType x)

{

int i;

for(i=0;i<length;i++)

if(data[i]==x) return i+1;

return 0;

}

template<class DataType>

void SeqList<DataType>::Insert(int i,DataType x)

{

int j;

if(length>=MaxSize) throw"上溢";

if(i<1||i>length+1) throw"位置";

for(j=length;j>=i;j--)

data[j]=data[j-1];

data[i-1]=x;

length++;

}

template<class DataType>

DataType SeqList<DataType>::Delete(int i)

{

int x,j;

if(length==0) throw"下溢";

if(i<1||i>length) throw"位置";

x=data[i-1];

for(j=i;j<length;j++)

data[j-1]=data[j];

length--;

return x;

}

template<class DataType>

void SeqList<DataType>::PrintList()

{

int i;

for(i=0;i<length;i++)

cout<<data[i]<<endl;

}

# include"SeqList.cpp"

# include<iostream>

using namespace std;

int main()

{

int r[10],i;

for(i=0;i<10;i++)

cin>>r[i];

SeqList<int>S(r,10);

S.PrintList();

cout<<"The Second grade is "<<S.Get(2)<<endl;

cout<<"The Location of 90 is "<<S.Locate(90)<<endl;

S.Insert(3,65);

S.Delete(2);

S.PrintList();

return 0;

}

程序结果:



猜你喜欢

转载自blog.csdn.net/LIU_JY_/article/details/80149025