//链表写,先写建立链表的函数,再输出
#include <stdio.h>
#include <stdlib.h>#define LEN sizeof(struct Student) //struct Student长度
struct Student
{
char num[10];
char name[10];
int score;
struct Student *next;
};
int n; // n是结点个数
struct Student *creat() //调用指针类型的creat函数,返回一个指针值
{
struct Student *head,*p1,*p2;
n=0;
p1=p2=(struct Student *)malloc(LEN); //也可用隐式强制转换 p1=malloc(LEN);
//malloc带回的是不指向任何类型的指针
//开辟一个长度为LEN(即结构体Student的长度)的新单元,(struct Student *)使malloc返回的指针转换为struct类型数据的指针,*不可省略
head=NULL;
while(scanf("%s%s%d",p1->num,p1->name,&p1->score)!=EOF) //输入学生的学号、姓名和成绩{
if(p1->score==0)
break;
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct Student *)malloc(LEN);
}
p2->next=NULL;
return(head); //返回一个指向链表头的指针
}
void print(struct Student *head) //print函数输出链表
{
struct Student *p; //在函数中定义struct Student类型的变量p
p=head; //使p指向第一个结点
if(head!=NULL) //若不是空表
do
{
printf("%s %s %d\n",p->num,p->name,p->score); //输出一个结点值的学号、姓名、成绩
p=p->next; //p指向下一个结点
}while(p!=NULL); //当p不是“空地址”
}
int main()
{
struct Student *pt;
pt=creat(); //调用creat()
print(pt); //调用print()
return 0;
}