一个c语言改错题,求大神解答

求各位大神给看一下,这个题是个改错题,目的是统计专业人数,
,将其中编号为02的计算机专业学生输出。但是我改好后,发现第一个录入的学号无法被使用,如图,改了学号的次序后,结果不一样,求大神解答
图片说明图片说明

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
    char code[8];
    struct node *next;
};
int main()
{struct node *head,*p;
int i,n,count=0;
char str[8];
int size=sizeof(struct node);
head=NULL;
gets(str);
while(strcmp(str,"#")!=0)
{
p=(struct node*)malloc(size);
strcpy(p->code,str);
    p->next=head;
    head=p;
    gets(str);
}
for(p=head;p->next!=NULL;p=p->next)
if(p->code[1]=='0'&&p->code[2]=='2')
    count++;
printf("%d\n",count);
return 0;
}

你这个问题很明显啊,你说的第一个录入的学号无法被使用,以及改了学号的次序后,结果不一样都是由同一个问题引起的,就是第一个录入学号无效的问题
。你的head=NULL;这个是初始值,但是在
p->next=head;
head=p;
gets(str);
首先第一个录入的学号时hea的是NULL的,也即第一个录入学号时p->next=null;而你在下面判断时又是以p->next!=NUL来判断的,也就是说你第一个数据因为是p->next ==NUL,所以导致第一个学号不执行,其他地方没问题

n=0; //add
while(strcmp(str,"#")!=0)
{
p=(struct node*)malloc(size);
strcpy(p->code,str);
n++; //add
p->next=head;
head=p;
gets(str);
}
//for(p=head;p->next!=NULL;p=p->next) del
p=head;

for(i=0;i<n;i++)

{
if(p->code[1]=='0'&&p->code[2]=='2')
count++;
p=p->next
}

printf("%d\n",count);
return 0;
}

这样就OK了,当然你也可以使用其他方式。经过测试是OK的,请采纳!!!