2..建立一个由n个学生成绩的顺序表,实现对数据的插入,删除,查找等操作。
源代码:
#ifndef Student_H
#define Student_H
template<class DataType>
struct Node
{
DataType data;
Node<DataType>*next;
};
template<class DataType>
class Student
{
public:
Student();
Student(DataType a[],int n);
~Student();
void Insert(int i,DataType x);
int Locate(DataType x);
DataType Delete(int i);
void Print();
private:
Node<DataType>*first;
};
#endif
#include<iostream.h>
#include"Student.h"
template<class DataType>
Student<DataType>::Student()
{
first=new Node<DataType>;
first->next=NULL;
}
template<class DataType>
Student<DataType>::Student(DataType a[],int n)
{
Node<DataType>*r,*s;
first=new Node<DataType>;
r=first;
for(int i=0;i<n;i++)
{
s=new Node<DataType>;
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
template<class DataType>
Student<DataType>::~Student()
{
Node<DataType>*q=NULL;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
template<class DataType>
void Student<DataType>::Insert(int i,DataType x)
{
Node<DataType>*p=first,*s=NULL;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL) throw"成绩不存在";
else
{
s=new Node<DataType>;
s->data=x;
s->next=p->next;
p->next=s;
}
}
template<class DataType>
int Student<DataType>::Locate(DataType x)
{
Node<DataType>*p=first->next;
int count=1;
while(p!=NULL)
{
if(p->data==x)return count;
p=p->next;
count++;
}
return 0;
}
template<class DataType>
DataType Student<DataType>::Delete(int i)
{
Node<DataType>*p=first,*q=NULL;
DataType x;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL)
throw"成绩不存在";
else
{
q=p->next;
x=q->data;
p->next=q->next;
delete q;
return x;
}
}
template<class DataType>
void Student<DataType>::Print()
{
Node<DataType>*p=first->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
#include<iostream.h>
#include"Student.cpp"
void main()
{
double s[5]={85.5,67,48,91,76};
Student<double>S(s,5);
cout<<"该组学生成绩为:"<<endl;
S.Print();
try
{
S.Insert(3,84);
}
catch(char*s)
{
cout<<s<<endl;
}
cout<<endl;
cout<<"修改后的成绩为:"<<endl;
S.Print();
cout<<endl;
cout<<"成绩为84的位置是:";
cout<<S.Locate(84)<<endl;
cout<<endl;
cout<<"删除前的成绩:"<<endl;
S.Print();
try
{
S.Delete(2);
}
catch(char*s)
{
cout<<s<<endl;
}
cout<<endl;
cout<<"删除后的成绩为:"<<endl;
S.Print();
}
运行结果: