链表插入数据:为什么在成员函数insert中还要判断指针head是否为空指针?
问题描述:
在“list”这个类中的“list(){head=NULL}” 不是已经将“head”定义为空指针了吗?为什么在定义它的成员函数insert的时候还要判断是否为空指针?
class list
{
node *head;
public:
list(){head=NULL;}
void insertlist(int adata,int bdata);
void deletelist(int adata);
void outputlist();
node *gethead(){return head;}
};
void list::insertlist(int adata,int bdata)
{
node *q,*p,*s;
s=(node*)new(node);
s->data=bdata;
p=head;
if(head==NULL)
{
head=s;
s->next=NULL;
}
}
答
因为head并非恒为空指针。
list(){head=NULL;} 执行构造函数之后的确是空指针了
但是执行insertlist之后,下一次再执行的时候就不是了
所以要判断