c++连表问题
来源:百度知道 编辑:UC知道 时间:2024/06/23 22:13:38
#include<iostream.h>
class Node
{
public:
Node(){Next=NULL;}
int data;
Node *Next;
};
class List
{
public:
List(){current=head=NULL;}
Node *current;
Node *head;
void addNode(Node* node);
void listAll();
};
void List::addNode(Node* node)
{
if(head==NULL)
{
head=current=node;
}
else
{
current->Next=node;
current=node;
}
}
void List::listAll()
{
while(head!=NULL)
{
cout<<head->data<<endl;
head=head->Next;
}
}
void main()
{
List *l = new List(); //为什么不能
改称List l = new List(); l.addNode(n);l.listAll()的话不行呢
for(int i =1;i<=10;i++)
{
Node *n=new Node();
n->data=i;
l->addNode(n);
}
l->listAll();
}
class Node
{
public:
Node(){Next=NULL;}
int data;
Node *Next;
};
class List
{
public:
List(){current=head=NULL;}
Node *current;
Node *head;
void addNode(Node* node);
void listAll();
};
void List::addNode(Node* node)
{
if(head==NULL)
{
head=current=node;
}
else
{
current->Next=node;
current=node;
}
}
void List::listAll()
{
while(head!=NULL)
{
cout<<head->data<<endl;
head=head->Next;
}
}
void main()
{
List *l = new List(); //为什么不能
改称List l = new List(); l.addNode(n);l.listAll()的话不行呢
for(int i =1;i<=10;i++)
{
Node *n=new Node();
n->data=i;
l->addNode(n);
}
l->listAll();
}
因为 new List()的返回值类型为 List * 类型的 ,而你的List l 是定义了List类型的对象
还不明白,
QQ:380208702
List l;
for(int i =1;i<=10;i++)
{
Node *n=new Node();
n->data=i;
l.addNode(n);
}
l.listAll();
把main()要这样改,
因为List l 创建的是对象不需要自己分配内存,List *l 是个指针对象需要自己主动分配内存空间的
改称List l = new List(); l.addNode(n);l.listAll()的话不行呢
List l:是创建了一个List型的对象,而new List()返回创建的对象的地址,把地址赋给变量是错误的,应赋给指针变量,于是写成List *l = new List();
另外,不用由new创建的对象时,要及时用delete释放内存空间,防止内存泄漏