实验3:线性表综合-顺序表
1. 建立一个由n个学生成绩的顺序表,n 的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。
#include<iostream.h>const int Max=38;
class SeqList{
public:
SeqList(float score[],int n); //构造函数,建立一个长度为n的顺序表
~SeqList(){} //析构函数
void Insert(int i,float x); //插入操作,在位置i插入元素x
float Delete(int i); //在位置i删除对应元素
float Get(int i); //按位查找,找位置i的元素
int Locate(float x); //按值查找,找数值为x的元素
void Print(); //遍历操作,按序号依次输出各元素
private:
float data[Max]; //存放数据元素的数组
int length; //线性表的长度
};
SeqList::SeqList(float score[],int n) //构造函数
{
if(n>Max)throw"参数非法";
for(int i=0;i<n;i++)
data[i]=score[i];
length=n;
}
void SeqList::Insert(int i,float x) //插入操作
{
int j;
if(length>Max)throw"上溢";
if(i<1||i>=Max)throw"位置非法";
for(j=length;j>=i;j--)
data[j]=data[j-1];
data[i-1]=x;
length++;
}
float SeqList::Delete(int i) //删除操作
{
float p;int j;
if(length==0)throw"下溢";
if(i<1||i>=Max)throw"位置非法";
p=data[i-1];
for(j=i;j<length;j++)
data[j-1]=data[j];
length--;
return p;
}
float SeqList::Get(int i) //按位查找
{
if(i<1&&i>=length)throw"查找位置非法";
else return data[i-1];
}
int SeqList::Locate(float x) //按值查找
{
for(int i=0;i<length;i++)
if(data[i]==x) return i+1; //返回元素序号
return 0;
}
void SeqList::Print() //输出操作
{
for(int i=0;i<length;i++)
{
cout<<"number "<<i+1<<" score: "<<data[i];
if(i%2==0&&i!=1)cout<<endl;
else cout<<" ";
}
}
void main()
{
float score[10]={90.5,58,80,55.5,99,81.5,85,89.5,70.5,69.5};
SeqList student(score,10);
cout<<"学生成绩:"<<endl;
student.Print();
cout<<endl<<endl<<"在位置4插入成绩56,结果如下:"<<endl;
student.Insert(4,56);
student.Print();
cout<<endl<<"在位置6删除成绩:"<<student.Delete(6)<<endl<<"删除后结果如下:"<<endl;
student.Print();
cout<<endl<<endl<<"位置6的成绩:"<<student.Get(6)<<endl;
cout<<"成绩81.5所在的位置:"<<student.Locate(81.5)<<endl;
}