今天也是想找到工作的一天 2018-12-13 14:48 采纳率: 100%
浏览 576
已采纳

链表插入数据:为什么在成员函数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;
    }
}
  • 写回答

1条回答 默认 最新

  • threenewbee 2018-12-13 14:59
    关注

    因为head并非恒为空指针。
    list(){head=NULL;} 执行构造函数之后的确是空指针了
    但是执行insertlist之后,下一次再执行的时候就不是了
    所以要判断

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?