实验三 单链表实现学生成绩管理

代码实现:

#include<iostream>

using namespace std;
struct node
{
float data;
node* next;
};
class student
{
node* first,*p,*q;
public:
student();
student(float a[],int n);       //建立n个元素的单链表
~student();
int leng();   //求单链表的长度
float get(int i);   //按位查找,查找第i个结点的元素值
int locate(float x);   //按值查找
void insert(float x,int i);     //插入操作,在第i个位置插入元素值为x的结点
float dele(int i);    //删除操作,删除第i个结点
void print();  //遍历输出所有元素
};
student::student()
{first=new node;
first->next=NULL;
}
student::student(float a[],int n)    //
{first=new node;first->next=NULL;
for(int i=0;i<n;i++)
{
node* s=new node;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
student::~student()   //
{
while(first!=NULL)
{q=first;
first=first->next;
delete q;}
}


int student::leng()  //返回单链表的长度
{p=first->next;int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;
}
float student::get(int i)   //
{
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)
{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)    //头插法
{p=first->next;int count=1;
while(p!=NULL&&count<i-1)
{p=p->next;
count++;
}
if(p==NULL)throw"插入位置错误";
else {
node* s=new node;
    s->data=x;
s->next=p->next;
p->next=s;
}
}
float student::dele(int i)     //
{p=first;int count=0;
while(p!=NULL&&count<i-1)      //找到第i个结点
{
p=p->next;count++;
}
if(p==NULL||p->next==NULL)  throw"位置";
else {
float x;
q=p->next;x=q->data;
p->next=q->next;
delete q;
return x;
}}
void student::print()
{p=first->next;
while(p!=NULL)
{cout<<p->data<<"\t";
p=p->next;
}
}
void main()
{
float a[7]={89,88,87.5,86,85,84,83};
student s(a,7);
cout<<"**********************\n"<<"单链表实现学生成绩操作\n"<<"**********************\n";
cout<<"共有"<<s.leng()<<"位学生成绩"<<endl;
s.print();
cout<<"把90分的学生成绩插入到第4位 "<<endl;
try{
s.insert(90,4);}
catch(char *s)
{
cout<<s<<endl;}
cout<<"把89分的学生成绩插入到第10位   ";
try{
s.insert(89,10);}
catch(char *s)
{
cout<<s<<endl;}
s.print();
try{
cout<<"查找第6位成绩值为: "<<s.get(6)<<endl;
}
catch(char *s)
{
cout<<s<<endl;}
try{
cout<<"删除第5位的元素值为"<<s.dele(5)<<endl;}
catch(char *s)
{
cout<<s<<endl;}
s.print();
cout<<"查找成绩为88的是第 "<<s.locate(88)<<" 位"<<endl;

}


猜你喜欢

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