#include<iostream.h>
template<class DataType>
struct Node
{
DataType grade;
Node<DataType>*next;
};
template<class DataType>
class Student
{
public:
Student();
Student(DataType g[],int n);
~Student();
int locate(DataType x);
void insert(int i,DataType x);
DataType Delete(int i);
void printlist();
private:
Node<DataType>*first;
};
template<class DataType>
Student<DataType>::Student()
{
first=new Node<DataType>;
first->next=NULL;
}
template<class DataType>
Student<DataType>::Student(DataType g[],int n)
{
Node<DataType>*r,*s;
first=new Node<DataType>;
r=first;
for(int i=0;i<n;i++)
{
s=new Node<DataType>;
s->grade=g[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->grade=x;
s->next=p->next;p->next=s;
}
}
template<class DataType>
DataType Student<DataType>::Delete(int i)
{
Node<DataType>*p=first,*q=NULL;
DataType g;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL)
throw"位置非法";
else{
q=p->next;g=q->grade;
p->next=q->next;
delete q;
return g;
}
}
template<class DataType>
int Student<DataType>::locate(DataType x)
{
Node<DataType>*p=first->next;
int count=1;
while(p!=NULL)
{
if(p->grade==x)return count;
p=p->next;
count++;
}
return 0;
}
template<class DataType>
void Student<DataType>::printlist()
{
int i=0;
Node<DataType>*p=first->next;
while(p!=NULL)
{
i=i+1;
cout<<"第"<<i<<"个学生成绩:";
cout<<p->grade<<" ";
p=p->next;
cout<<endl;
}
cout<<endl;
}
void main()
{
int g[5]={99,95,91,88,94};
Student<int>S(g,5);
cout<<"执行插入操作前学生的成绩为:"<<endl;
S.printlist();
try
{
S.insert(2,70);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"插入第二个学生成绩后的数据为:"<<endl;
S.printlist();
cout<<"成绩为88的学生位置为:";
cout<<S.locate(88)<<endl;
cout<<"执行删除第一个学生成绩前的数据为:"<<endl;
S.printlist();
try
{
S.Delete(1);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"执行删除第一个学生成绩后的数据为:"<<endl;
S.printlist();
}
实验三 单链表
最新推荐文章于 2023-07-27 20:10:03 发布