69,373
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<malloc.h>
//int n=1; // 用来统计链表中节点个数。
int n=0; // 用来统计链表中节点个数。
struct Student
{
int num;
float score;
struct Student * next;
};
int main()
{
struct Student * head;
struct Student * creat(); // 输入函数的声明
void print(struct Student * head); // 输出函数
head=creat();
print(head);
return 0;
}
struct Student * creat()
{
struct Student *head;
struct Student *p1,*p2;
head=NULL;
p1=p2=(struct Student *)malloc(sizeof(struct Student));
scanf("%d%f",&p1->num,&p1->score);
// 输入第一个节点的数据
while(p1->num!=0)
{
n++;
if(n==1)
head=p1;
else {
p2->next=p1;
p2=p1;
}
// 接着再开辟一个新的节点
p1 = (struct Student *)malloc(sizeof(struct Student));
scanf("%d%f",&p1->num,&p1->score);
}
free(p1); //最后一个几点需要释放掉,因为并没有链入链表中
p2->next=NULL;
printf("n = %d\n", n);
return (head);
}
void print(struct Student * head)
{
struct Student * p;
int i;
printf("the %d records are :\n",n);
printf("num score\n");
for(i=0,p=head; i < n; i++) {
printf("%d %f\n",p->num,p->score);
p=p->next;
}
}