代码如下:
#include <stdio.h>
#include<stdlib.h>
struct Student
{
long num;
float score;
struct Student *next;
};
struct Student *creat()
{
struct Student *head=NULL,*p=NULL;
p=(struct Student *)malloc(sizeof(struct Student));
scanf("%ld,%f",&p->num,&p->score);
while(p->num!=0)
{
if(head==NULL) //如果这是插入的第一个结点,此节点就是最后一个结点
{
p->next=NULL; //那么它的next就指向空,即在其后没有结点了
head=p;
}
else //如果不是,代表这不是插入的第一个结点,
//即不是链表中最后一个结点
{
p->next=head; //则使next指向head
head=p; //然后再让head为p的地址,从而相连
}
p=(struct Student *)malloc(sizeof(struct Student));
scanf("%ld,%f",&p->num,&p->score); //这里是开辟一个新的动态空间,
//用来存放下一个结点
}
free(p);
return head;
}
void print(struct Student *head)
{
struct Student *p;
if(head==NULL) //如果head为NULL,即为形成链表
{
printf("Empty!\n");
return;
}
p=head; //head为插入的最后一个结点,也是链表的第一个结点
printf("Scores are:\n");
if(p!=NULL)
do
{
printf("num:%ld,score:%.2f\n",p->num,p->score);
p=p->next;
}while(p!=NULL); //第一次插入的指针,也是链表的最后一个节点,其next指向为空
}
int main()
{
struct Student *creat();
void print(struct Student *head);
struct Student *pt;
pt=creat();
print(pt);
return 0;
}
运行结果如下: