动态链表初试(错误)

来源:互联网 发布:mdb数据库 编辑:程序博客网 时间:2024/06/03 18:49

错误程序一篇,昨天下午搞了半天没弄明白,今天晚上又用了一个多小时才搞懂。。。

结论:链表不能随便传递,因为链表有两部分,一部分是数值,另外一部分是指向下一个节点的指针。。。


数据依然来自score.txt,在程序中建立一个动态链表:每读入一个同学的数据,计算总分,分配结点的存储空间并赋值,并建立起前后相链的关系。在建立链表的同时,要进行统计,以便于求出所有同学总分的平均成绩。动态链表建立后,从头结点开始,依次输出所有总分高于平均总分且没有挂科的同学的学号、姓名、总分。

#include <iostream>#include<fstream>#include<cstdlib>#include<iomanip>using namespace std;struct Score{char num[14];char name[10];int cpp;int math;int english;int sum;Score *next;friend istream &operator >>( istream &is, Score &a){is>>a.num>>a.name>>a.cpp>>a.math>>a.english;return is;}friend ostream &operator<<(ostream &os,const Score &a){os<<a.num<<" "<<left<<setw(6)<<a.name<<" "<<a.cpp<<" "<<a.math<<" "<<a.english<<"  "<<a.sum;return os;}};int main(){ifstream infile;infile.open("haohaoxuexi.txt");if(!infile){cerr<<"file can not open"<<endl; exit(1);}Score *head,*p,*q;//while(infile>>a[i]){a[i].sum=0;a[i].sum=a[i].cpp+a[i].math+a[i].english;i++;}    for(int i=0;i<4;i++){p=new Score;p->next=NULL;infile>>*p;if(0==i)head=p;else q->next=p;q=p;}    infile.close();    Score *rep;    rep=head;//     for(int j=0;j<10;j++)    while(rep!=NULL){rep->sum=rep->cpp+(*rep).math+rep->english;cout<<*rep<<endl;rep=rep->next;}//链表冒泡排序法         Score *rep2,*rep3,*rep5;         rep2=new Score;         rep3=head; for(int i=0;i<8;i++){              if(rep3->sum  < rep3->next->sum)      {                     *rep2=*rep3;                     *rep3=*rep3->next;                     *(rep3->next)=*rep2;               }              //   cout<<"i="<<i<<endl;            rep3=rep3->next;            }         cout<<endl; rep5=head;// while(rep5!=NULL)         for(int i=0;i<9;i++) {cout<<*rep5<<endl;rep5=rep5->next; }//     //输出前拿奖金(总分高,无挂科)//     cout<<endl;//     cout<<"拿奖学金的人名单:"<<endl;//     int num=0;//     for(int i=0;i<10;i++)// {// if(a[i].cpp>=60&&a[i].math>=60&&a[i].english>=60)//{cout<<a[i]<<endl;num++;}//if(3==num)break;// }return 0;}


0 0
原创粉丝点击