奇怪的全局结构指针,郁闷了一下午了,请教各位!
调试平台WIN XP VC++6.0
#include <iostream.h>
struct Student
{
long number;
float score;
Student *next;
};
Student* head;
Student* Create()
{
Student* pS;
Student* pEnd;
pS=new Student;
cin>>pS->number>>pS->score;
head=NULL;
pEnd=pS;
while (pS->number!=0)
{
if (head==NULL)
head=pS;
else
pEnd->next=pS;
pEnd=pS;
pS=new Student;
cin>>pS->number>>pS->score;
}
pEnd->next=NULL;
delete pS;
return (head);
}
void ShowList(Student* head)
{
while (head)
{
cout<<head->number<<","<<head->score<<endl;
head=head->next;
}
}
void Insert(Student* head,Student* stud)
{
if (head==NULL)
{
head=stud;
stud->next=NULL;
return ;
}
else if (head->number>stud->number)
{
stud->next=head;
head=stud;
return ;
}
else
{
Student* pGuard=head;
while ((pGuard->next)&&((pGuard->next->number)>(stud->number)))
{
stud->next=pGuard->next;
pGuard->next=stud;
}
return ;
}
}
void main()
{
Student ps;
ps.number=36;
ps.score=3.8;
head=Create();
Insert(head,&ps);//全局head的地址无任何改变
ShowList(head);
}
////////按照以下的写法就OK,不知道为什么///////////////
#include <iostream.h>
struct Student
{
long number;
float score;
Student *next;
};
Student* head;
Student* Create()
{
Student* pS;
Student* pEnd;
pS=new Student;
cin>>pS->number>>pS->score;
head=NULL;
pEnd=pS;
while (pS->number!=0)
{
if (head==NULL)
head=pS;
else
pEnd->next=pS;
pEnd=pS;
pS=new Student;
cin>>pS->number>>pS->score;
}
pEnd->next=NULL;
delete pS;
return (head);
}
void ShowList(Student* head)
{
while (head)
{
cout<<head->number<<","<<head->score<<endl;
head=head->next;
}
}
Student* Insert(Student* head,Student* stud)
{
if (head==NULL)
{
head=stud;
stud->next=NULL;
return head;
}
else if (head->number>stud->number)
{
stud->next=head;
head=stud;
return head;
}
else
{
Student* pGuard=head;
while ((pGuard->next)&&((pGuard->next->number)>(stud->number)))
{
stud->next=pGuard->next;
pGuard->next=stud;
}
return head;
}
}
void main()
{
Student ps;
ps.number=36;
ps.score=3.8;
head=Create();
head=Insert(head,&ps);
ShowList(head);
}