如何用C++实现链表?
#include <iostream>
using namespace std;

typedef struct Student{
    char Num[12];   // 学号
    char Name[10];  //姓名
    int age;        //年龄    
    float score;    //成绩
    Student *next;
}Stu;

void CreateList(Stu* &L,int n){ //(1)将随机输入的n个学生(信息),构成一个不带头结点的链表L
    int i;
    Stu *temp,*tail;
    tail=L;

    cout<<"Please input "<<n<<" students' information(Num,Name,age and score:\n";
    for(i=1;i<=n;i++){
        temp=new Stu;
        temp->next=NULL;

        cin>>temp->Num>>temp->Name>>temp->age>>temp->score;

        if(tail==NULL)     L=temp;        
        else    tail->next=temp;

        tail=temp;
    }
}

int Length(Stu *L){
    Stu* temp=L; 
    int count=0;

    while(temp!=NULL){
        count++;
        temp=temp->next;    
    }
    return count;
}
    
void Display(Stu* L){ //(2)用递归方法遍历链表,即输出各结点的信息
    if(L==NULL) return;
    else{
        cout<<L->Num<<","<<L->Name<<","<<L->age<<","<<L->score<<endl;
        Display(L->next);
    }
}

float MaxScore(Stu* L){ //(2)计算链表中结点的最大成绩
    Stu* temp=L->next;
    float maxscore=L->score;

    while(temp!=NULL){
        if(temp->score>maxscore) maxscore=temp->score;
        temp=temp->next;
    }
    return maxscore;
}

float Average(Stu* L){//(2)计算链表中所有结点的平均成绩
    Stu* temp=L; 
    float sum=0;int count=0;

    while(temp!=NULL){
        sum+=temp->score;
        count++;
        temp=temp->next;    
    }
    return sum/count;
}

void main(void){
    Stu* List=NULL;
    CreateList(List,3);
    
    cout<<endl;    
    cout<<"the length of the list is "<<Length(List)<<endl;

    Display(List);
    cout<<endl;

    cout<<"the highest score is "<<MaxScore(List)<<endl;
    cout<<"the average score is "<<Average(List)<<endl;
}
博客签名:敬畏生命,珍惜时间,热爱生活。