creatlist用来建立一个带头结点的学生数据的单向链表,新的结点总是差在链表的末尾。链表的头指针作为函数值返回,链表最后一个结点的next域放入NULL,作为链表的结束标志,学号为0不存入链表。
#include <stdio.h>
#include <malloc.h>
#define LEN sizeof(struct student)
struct student {
long num;
float score;
struct student *next;
};
int n;
struct student* creatlist() {
struct student* head ,*p1,*p2;
p1=p2=(struct student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
head=NULL;
n=0;
while (p1->num!=0){
n=n+1;
if (n==1)
head=p1;
else
p2->next=p1;
// if (head==NULL)
// head=p1;
// else
// p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
}
p2->next=NULL;
free(p1);
return head;
}
int main(){
struct student *pt;
pt=creatlist();
printf("\nnum:%ld\nscore:%5.1f\n",pt->num,pt->score);
}