【发布时间】:2012-06-05 03:29:48
【问题描述】:
Insert 是一种将项目附加到我的链表末尾的方法。
不知道如何为 Node 为空的情况编写代码,我只想添加。
struct Node{
int data;
Node *next;
Node(int data):data(data),next(NULL){}
void insert(int data){
if (this==NULL){
this=new Node(data); // compiler is complaining here.
// how would I go about setting the value of this (which is presently NULL) to a new Node?
}
}
}
【问题讨论】:
-
如果
this是NULL,你是如何使用它的成员的?this怎么会是NULL呢? -
以下是什么?节点 *n = NULL;
-
这是一个指向
Node的指针。没有Node是从那里创建的。那里的NULL只是表示它没有指向任何东西。 -
@user1202422:您不能在空指针上调用成员。
thisininsert是Node const *(即不能更改)...你需要重新审视你的设计,考虑你想append一个新的Node到 list...也许您错过了列表? -
所以如果我这样做了:n = new Node; n.插入(5); // 这一步,插入不是在空节点上运行吗?
标签: c++ class linked-list this