一.实验目的
巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。
二..实验内容
1.建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。
要求如下:
1)用顺序表来实现。
2)用单链表来实现。
3)用双链表实现。
4)用静态链表实现。
5)用间接寻址实现。
三、代码
有参构造函数
template
Score::Score(DataType a[],int n)
{
int i;
if(n>MaxSize)
throw "location";
for(i=0;i
按位置查找成绩
template //按位查找
DataType Score::Get( int i)
{
if(i<1||i>length)
throw"查找位置非法";
else return data[i-1];
}
按值查找位置
template //按值查找
int Score::Locate(DataType x)
{
int i;
for(i=0;i
插入成绩
template
void Score::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
DataType Score::Delete(int i)
{
int x,j;
if(length==0)
throw"下溢";
if(i<1||i>length)
//throw"位置异常";
x=data[i-1];
for(j=i;j
输出成绩
template
void Score::Print()
{
int i;
for(i=0;i#include
using namespace std;
const int MaxSize=100;
template
class Score
{
public:
Score(){ length=0; } //建立空的顺序表
Score(DataType a[],int n); //建立长度为n的顺序表
~Score(){} //建立析构函数
int Length(){ return length;} //求线性表的长度
DataType Get( int i); //按位置查找
int Locate(DataType x); //按值查找
void Insert(int i,DataType x); //在位置i插入x
DataType Delete(int i); //删除
void Print(); //输出
private:
DataType data[MaxSize]; //存放数据元素的数组
int length; //线性表的长度
};
template
Score::Score(DataType a[],int n)
{
int i;
if(n>MaxSize)
throw "非法参数";
for(i=0;i //按位查找
DataType Score::Get( int i)
{
if(i<1||i>length)
throw"查找位置非法";
else return data[i-1];
}
template //按值查找
int Score::Locate(DataType x)
{
int i;
for(i=0;i
void Score::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
DataType Score::Delete(int i)
{
int x,j;
if(length==0)
throw"下溢";
if(i<1||i>length)
//throw"位置异常";
x=data[i-1];
for(j=i;j
void Score::Print()
{
int i;
for(i=0;is(a,10);
while(flag==0)
{
cout<<"please input the command(1~8):"<>t;
switch(t)
{
case 1:
l=s.Length();
cout<<"the length is:"<>i;
x=s.Get(i);
cout<<"the number is:"<>x;
i=s.Locate(x);
cout<<"the number's location is:"<>i;
cout<<"please input the insert number:"<>x;
s.Insert(i,x);
cout<<"insert successfully!"<>i;
s.Delete(i);
cout<<"delete successfully!"<
运行结果:
求长度
按位置查找成绩

按值查找位置


插入成绩

删除成绩

输出所有成绩

输出菜单界面

退出
