代码如下:
头文件:
#ifndef SeqList_H
#define SeqList_H
const int Maxsize=100;
class SeqList
{
public:
SeqList(){length=0;}
SeqList(int a[],int n);
~SeqList(){}
void Insert(int i,int x);
int Delete(int i);
int Locate(int x);
void PrintList();
private:
int data[Maxsize];
int length;
};
#endif
源程序文件:
#include<iostream>
using namespace std;
#include"SeqList.h"
SeqList::SeqList(int a[],int n)
{
if(n>Maxsize)throw"参数非法";
for(int i=0;i<n;i++)
data[i]=a[i];
length=n;
}
void SeqList::Insert(int i,int x)
{
if(length>=Maxsize)throw"上溢";
if(i<1||i>length+1)throw "位置非法";
for(int j=length;j>=i;j--)
data[j]=data[j-1];
data[i-1]=x;
length++;
}
int SeqList::Delete(int i)
{if(length==0) throw"下溢";
if(i<1||i>length)throw"位置非法";
int x=data[i-1];
for(int j=i;j<length;j++)
data[j-1]=data[j];
length--;
return x;
}
int SeqList::Locate(int x)
{
for(int i=0;i<length;i++)
if(data[i]==x)return i+1;
else throw"位置非法";
return 0;
}
void SeqList::PrintList()
{
for(int i=0;i<length;i++)
cout<<data[i]<<" ";
cout<<endl;
}
源程序文件2:
#include<iostream>
using namespace std;
#include"SeqList.h"
void main()
{
int r[100],h,z;
cout<<"需要录入成绩的学生人数:"<<endl;
cin>>h;
for(z=0;z<h;z++)
{cout<<"第"<<z+1<<"个学生的成绩:"<<endl;
cin>>r[z];
}
SeqList L(r,h);
cout<<"执行插入操作前学生们的成绩分别为:"<<endl;
L.PrintList();
try
{int b,xcj;
cout<<"新的学生成绩插入在第几个位置之后:"<<endl;
cin>>b;
cout<<"新的学生成绩为:"<<endl;
cin>>xcj;
L.Insert(b+1,xcj);
}
catch(char *s)
{cout<<s<<endl;
}
cout<<"执行插入操作后成绩为:"<<endl;
L.PrintList();
try
{int o;
cout<<"需要删除第几个学生的成绩"<<endl;
cin>>o;
L.Delete(o);}
catch(char *s)
{cout<<s<<endl;
}
cout<<"删除该学生的成绩后为:"<<endl;
L.PrintList();
int zbb;
cout<<"要查找的学生成绩为:"<<endl;
cin>>zbb;
cout<<"该学生的序号为"<<L.Locate(zbb)<<endl;}
编译结果如下:
原文链接:https://www.f2er.com/datastructure/382882.html