目标:创建一个链表,并将链表输出。结构体中包括学号与分数。链表以输入学号为0作为结束。输出模版为 No.学号 Score:分数
输入样例:
10101 98
10102 97
10103 100
10104 99
0 0
输出样例:
No.10101 score:98
No.10102 score:97
No.10103 score:100
No.10104 score:99
完成程序源代码
#include <stdio.h>
#include <stdlib.h>
struct student* create();
void print(struct student*);
struct student
{
int num;
int score;
struct student* next;
};
int main()
{
struct student* head;
head=create();
print(head);
return 0;
}
struct student* create()
{
struct student *head,*p1,*p2;
head=malloc(sizeof(struct student));
scanf("%d %d",&head->num,&head->score);
p1=malloc(sizeof(struct student));
p2=head;
p2->next=p1;
while(p2->num!=0)
{
scanf("%d %d",&p1->num,&p1->score);
if(!p1->num)
{
p2->next=NULL;
break;
}
p2=p1;
p1=malloc(sizeof(struct student));
p2->next=p1;
}
p2->next=NULL;
return head;
}
void print(struct student* head)
{
struct student* p1=head;
while(p1!=NULL)
{
printf("No.%d score:%d\n",p1->num,p1->score);
p1=p1->next;
}
}
程序易错点: if(!p1->num)
没有这句话判断结束标志并及时退出的话,就会将结束标志引入链表,造成无用数据的出现,导致错误。