一个有问题的C++链表程序

来源:百度知道 编辑:UC知道 时间:2024/05/22 12:23:44
#include<iostream.h>
struct Node
{
char name[20];
int grade;
Node*next;
};
void AA(Node*&head)
{
Node*s,*p;
s=new Node;
cin>>s->name;
cin>>s->grade;

for(int m=1;m<3;m++)
{

if(head==NULL)
head=s;
else
p->next=s;
p=s;
s=new Node;
cin>>s->name;
cin>>s->grade;

}

p->next=NULL;
delete s;
return;
}
void BB(Node*head)
{
while(head)
{
cout<<head->name<<'\t';
cout<<head->grade<<endl;
head=head->next;

}

}
void main()
{
Node*head=NULL;
AA(head);
BB(head);
}

为什么输入三位学生成绩只输出两位学生的成绩?????帮忙修改一下~~谢谢各位大师了!!!有加分

改为:
void AA(Node*&head)
{
Node*s,*p;
s=new Node;
cin>>s->name;
cin>>s->grade;

for(int m=1;m<3;m++)
{

if(head==NULL)
head=s;
else
p->next=s;
p=s;
s=new Node;
cin>>s->name;
cin>>s->grade;
}
p->next=s;
s->nest=null;
delete s;
return;
}
第三个结点悬在外边,没连在链表上,当然只输出两个啦

for(int m=1;m<3;m++)
改为for(int m=1;m<=3;m++)

void AA(Node*&head)
{
Node*s,*p;
s=new Node;
cin>>s->name;
cin>>s->grade;

for(int m=1;m<3;m++)
{

if(head==NULL)
{ head=p=s; //注意这里,你的问题应该就是因为没给P出值
s->next=null ;//这句也要加,不然会死循环的
}
else
p->next=s;
p=s;
s=new Node;
cin>>s->name;
cin>>s->grade;

}

去掉for循环前面的
s=new Node;
cin>>s->name