读取位置时发生访问冲突(关于求链表长度)

2024-11-28 00:00:58
推荐回答(1个)
回答1:

#include
struct student
{
int num;
int score;
struct student *next;
};int n;
struct student *creat(void)
{
struct student *p1,*p2,*head;
head=NULL;n=0;
p1=p2=(struct student *)malloc(sizeof(struct student));
//这个p1没有赋值,不知道你要怎么处理
scanf("%d %d",&p1->num,&p1->score); //我给你这么改好了吧
while(p1->num!=0)
{
n+=1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct student *)malloc(sizeof(struct student)); //新节点
scanf("%d %d",&p1->num,&p1->score);
}
p2->next=NULL;
return(head);
}
void print(struct student *head)
{struct student *p;
p=head;
while(p!=NULL){
printf("%d %d\n",p->num,p->score);
p=p->next;
}; //这个改下!!条件不是head!=NULL 啊
}
int main(int argc,char **argv)
{
struct student *head;
head=creat();
print(head);
return 0;}
这样就可以了