代码实现如下:
#include<iostream> using namespace std; const int max=20; struct node { float data; }; class student { node *a[max]; int length; public: student(); student(float b[],int n); ~student(){} int getlength(){return length;} float get(int i); int locate(float x); void insert(float x,int i); void dele(int i); void print(); }; student::student() {length=0; for(int i=0;i<max;i++) {a[i]=new node; a[i]=NULL;} } student::student(float b[],int n) {length=n; for(int i=0;i<n;i++) {a[i]=new node; a[i]->data=NULL;} for(i=0;i<n;i++) { a[i]=new node; a[i]->data=b[i]; } } float student::get(int i){ //按位查找 if(i>length||i<=0) throw"查找位置错误"; return a[i-1]->data; } int student::locate(float x) //按值查找 { for(int i=0;i<length;i++) {if(a[i]->data==x) return i+1;} return 0; //返回值为0时查找失败 } void student::insert(float x,int i) //插入操作 { if(i>max||i<1||i>length+1) throw"插入失败"; for(int j=length;j>=i;j--) { a[j]=a[j-1]; } length++; a[i-1]=new node; a[i-1]->data=x; } void student::dele(int i) //删除操作 { if(length==0) throw"下溢"; if(i<1||i>length) throw"位置"; for(int j=i;j<length;j++) a[j-1]=a[j]; length--; } void student::print() //遍历输出 { cout<<"学生成绩为:"; for(int i=0;i<length;i++) cout<<a[i]->data<<" "; cout<<endl; } void main() //主函数 { float score[5]={78,79,80,81,84.5}; student s1,s(score,5); cout<<"*******共有"<<s.getlength()<<"位学生成绩*******"<<endl; s.print(); try{ cout<<"***查找第三位学生成绩:"; cout<<s.get(3)<<endl;} catch(char *s) {cout<<s<<endl;} cout<<"***查找成绩为50是第"<<s.locate(50)<<"位\n"; cout<<"***查找成绩为80是第"<<s.locate(79)<<"位\n"; cout<<"***插入86分到第四位"<<endl; try{ s.insert(86,4);} catch(char *s) { cout<<s<<endl; } cout<<"*******共有"<<s.getlength()<<"位学生成绩*******"<<endl; s.print(); cout<<"***删除第三位学生成绩\n"; try{ s.dele(3);} catch(char *s) { cout<<s<<endl; } s.print(); }
运行结果图:
实验感想:原本就差插入与删除函数,以为就快写完了。结果就这两个函数拖了我几个小时。还好最后通过查找资料找到了自己的问题所在。数据结构代码的实现很重要,有是就是思路清晰,可是写出来的程序运行结果却不是想要的。应该多练多看书才对。