一、原题
建立学生信息链表(student.cpp)
题目描述
给出n个学生的姓名和年级,请建立一个学生信息的链表。并将链表中各元素依次输出。
输入
第一行:一个整数n
接下来n行,每行一个学生的名字和年龄。
输出
n行,每行包括学生的姓名和年龄。
样例输入
3
wuzhenghao 18
liudeyu 20
liuying 19
样例输出
wuzhenghao 18
liudeyu 20
liuying 19
提示
要求建立学生链表。
二、分析
根据题目意思,这道题要用链表来做(请自觉),点击这里获取关于链表的信息。然后我们先要定义一个结构体,在结构体里面定义一个结构体指针。如下:
struct student{
char name[100];
int age;
student *next;//结构体指针
};//定义一个结构体
第一个人的数据要经过特殊处理,所以要定义一个head,专门存储第一个人。然后设置下一个人为空,然后定义一个结构体为上一个数,能为后面输出的链表提供便利。循环n-1次重复进行。指针p为目前一个,好为链表提供便利。然后,后面输出,完成。详情请看下面的源代码。
三、源代码
#include<cstdio>
#include<iostream>
#include<cstring>
#include<time.h>
#include<algorithm>
#include<queue>
using namespace std;
void fre(){//读入输出函数
freopen("student.in","r",stdin);
freopen("student.out","w",stdout);
}
struct student{
char name[100];
int age;
student *next;//结构体指针
};//定义一个结构体
int main()
{
//fre();
int n;
cin>>n;//读入循环数量
student *head=new student;
cin>>head->name>>head->age;//读入头一个人的姓名和年龄
head->next=NULL;//设置下一个人暂时为空
student *p=head;//定义结构体
for(int i=1;i<n;i++){//循环n-1次
student *t=new student;//定义结构体
cin>>t->name>>t->age;//读入人的姓名和年龄
t->next=NULL;//设置这个人的下一个人暂时为空
p->next=t;//设置上一个人的下一个人为这个人
p=p->next;
}
for(p=head;p!=NULL;p=p->next)//输出
cout<<p->name<<" "<<p->age<<endl;
}