#include "stdafx.h"
#include<iostream>
using namespace std;
#define CULL 0
struct Node
{
Node(){next = NULL;}
int data;
Node * next;
};
class Clist
{
public:
Clist()
{
p_head = NULL;
}
bool insertList(int data)
{
Node * ps;
Node * temp;
ps = p_head;
if(p_head == NULL)
{
p_head = new Node;
p_head->data = data; //这句话如果我注释掉就不会出现内存错误,可是为什么呢?下面的我知道应该还需要判断,可是这句话为什么能影响错误呢?如果是1个node的时候添加node时候head->next=NULL的是吗?所以是缺少判断的,我理解的对吗?好心人快帮忙看看吧
p_head->next = NULL;
return CULL;
}
else
{
while(ps != NULL && ps->data<data)
{
temp = ps;
ps = ps->next;
}
ps = new Node;
ps->data = data;
ps->next = temp->next;
temp->next = ps;
}
return CULL;
}
void bianl()
{
Node * sp;
sp = p_head;
while(sp != NULL)
{
cout<<sp->data<<endl;
sp = sp->next;
}
}
private:
Node * p_head;
};
int _tmain(int argc, _TCHAR* argv[])
{
Clist sage;
//sage.insertList(10);
sage.insertList(20);
sage.insertList(100);
sage.insertList(2);
sage.insertList(37);
sage.insertList(12);
sage.insertList(5);
sage.bianl();
system("pause");
return 0;
}
temp不可能等于NULL
追答是有可能等于NULL的,你看你的判断:
while(ps != NULL && ps->datadata>data,这种情况下while循环是不进去的,temp就不被赋值,你在while循环外面使用temp,焉有不错之理?