用指针处理链表例题(二)

来源:互联网 发布:rsa密码算法 编辑:程序博客网 时间:2024/05/17 03:25

【题目】写一函数建立一个有3名学生数据的单向动态链表。

#include<stdio.h>#include<stdlib.h>#define LEN sizeof(struct student)int n;struct student{long num;float score;struct student *next;};struct student *create(){struct student *head,*p1,*p2;n=0;p1=p2=(struct student *) malloc(LEN);scanf("%ld %f",&p1->num,&p1->score);head=NULL;while(p1->num!=0){n++;if(n==1) head=p1;else p2->next=p1;p2=p1;p1=(struct student *)malloc(LEN);scanf("%ld %f",&p1->num,&p1->score);}p2->next=NULL;return(head);}int main(){struct student *p;p=create();for(int j=0;j<3;j++){printf("\nnum:%ld\nscore:%5.1f\n",p->num,p->score);p=p->next;}return 0;}