current position:Home>Solve what is wrong with my program

Solve what is wrong with my program

2022-08-06 09:23:18CSDN Q&A

This problem requires the implementation of a simple function that organizes the entered student grades into a singly linked list.
Zhejiang University PTA

Function interface definition:

void input();

The input is the information of several students (student number, name, grade), and it ends when the student number is 0.

Sample judge test procedure:

#include
#include
#include

struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *head, *tail;

void input();

int main()
{
struct stud_node *p;

head = tail = NULL;input();for ( p = head; p != NULL; p = p->next ) printf("%d %s%d\n", p->num, p->name, p->score);return 0;

}

/* Your code will be embedded here */

Here is my answer:
void input()
{
struct stud_node *p;
p = (struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d", &p->num);
while(p->num != 0)
{
scanf("%s %d", p->name, &p->score);
if(head==0)
{
head=p;
head->next=NULL;
}
tail=p;
p=(struct stud_node *)malloc(sizeof(struct stud_node));
p->next=NULL;
tail->next=p;
scanf("%d", &p->num);

}

}
My proofs
1 zhang 78
2 wang 80
3 li 75
4 zhao 85
0 0
target proofs
1 zhang 78
2 wang 80
3 li 75
4 zhao 85
Why do I output 0 0 more?

copyright notice
author[CSDN Q&A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/218/202207301820103516.html

Random recommended