C++链表的建立

#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;
}

第1个回答  2012-05-22
这其实是因为你没有为结点申请内存空间。C语言可以用malloc语句分配内存空间,比如给head结点分配内存可以这样写:head=(NODE *)malloc(sizeof(NODE));,C++可以用new来分配,head=new NODE();必须在分配了内存之后才能给结点赋值,否则程序不知道把值放在哪,就会报错。
第2个回答  2012-05-22
错误不在那里 错误在后面
在else 那一段,你仔细看看, ps->next = temp->next; 这个里面有漏洞,temp的判断可能存在遗漏,有一种情况可能导致temp=NULL,你少了这个判断。追问

temp不可能等于NULL

追答

是有可能等于NULL的,你看你的判断:
while(ps != NULL && ps->datadata>data,这种情况下while循环是不进去的,temp就不被赋值,你在while循环外面使用temp,焉有不错之理?

相似回答