实验三 双链表实现学生成绩处理

代码实现:

#include<iostream>
using namespace std;
struct node 
{
float data;
node *prior,*next;
};
class student
{
node* first;
public:
student();
student(float a[],int n);   // 
~student();
int leng();
float get(int i);
int locate(float x);
void insert(float x,int i);
void dele(int i);
void print();
};
student::student()
{node* first;
first->next=NULL;
}
student::student(float a[],int n)
{first=new node;first->next=NULL;
node* p=new node;
p=first;
for(int i=0;i<n;i++)
{node* s=new node;
s->data=a[i];
s->prior=p;
p->next=s;
s->next=NULL;
p=s;
}
}
student::~student()
{
node* p=new node;
while(first!=NULL)
{p=first;
first=first->next;
delete p;
}}
int student::leng()
{
node *p=new node;
p=first->next;int count=0;
while(p!=NULL)
{
p=p->next;
count++;}
return count;
}
float student::get(int i)
{
node* p=new node;p=first->next;
int count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;}
if(p==NULL)throw"查找位置错误";
else return p->data;
}
int student::locate(float x)
{
node* p=new node;
p=first->next;int count=1;
while(p!=NULL)
{
if(p->data==x) return count;
p=p->next;
count++;}
return 0;
}
void student::insert(float x,int i)
{
node* p=new node;
p=first;int count=0;
while(p!=NULL&&count<i-1)
{p=p->next;
count++;
}
if(p==NULL) throw"插入位置错误";
else {
node* s=new node;
s->data=x;s->prior=p;
s->next=p->next;
p->next->prior=s;
p->next=s;
}}
void student::dele(int i)
{node* p=new node;p=first;
int count=0;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL) throw"error";
else{
p->prior->next=p->next;
p->next->prior=p->prior;
delete p;}
}


void student::print()
{
node* q=new node;
q=first->next;
while(q!=NULL)
{
cout<<q->data;
cout<<" ";
q=q->next;
}
}
void main()
{
float a[5]={82,83.5,84,85,86};
student s(a,5);
cout<<"共有"<<s.leng()<<"位学生成绩"<<endl;
cout<<"学生成绩为 :";
s.print();
cout<<"接着删除第三位学生成绩"<<endl;
try
{s.dele(3);}
catch(char *s)
{cout<<s<<endl;}
cout<<"此时学生成绩为 :";
s.print();
try{cout<<"然后查找第三位学生成绩为 "<<s.get(3)<<endl;}
catch(char *s)
{cout<<s<<endl;}
try{cout<<"插入90分的成绩到第2位 "<<endl;
s.insert(90,2);}
catch(char *s)
{cout<<s<<endl;}
cout<<"此时学生成绩为 :";
s.print();
cout<<"查找分数为90的成绩为第"<<s.locate(90)<<"位"<<endl;
cout<<"查找分数为70的成绩为第"<<s.locate(70)<<"位"<<endl;
cout<<"若为第0位,则无该学生成绩"<<endl;

}




猜你喜欢

转载自blog.csdn.net/x1432553805/article/details/80200851