C++ C++;课程-我的程序有什么问题?
Insert是一种将项目附加到链接列表末尾的方法 我不知道如何为Node为null的情况编写代码,我只想对其进行添加C++ C++;课程-我的程序有什么问题?,c++,class,linked-list,this,C++,Class,Linked List,This,Insert是一种将项目附加到链接列表末尾的方法 我不知道如何为Node为null的情况编写代码,我只想对其进行添加 struct Node{ int data; Node *next; Node(int data):data(data),next(NULL){} void insert(int data){ if (this==NULL){ this=new Node(data);
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?
}
}
}
您不能为该指针赋值,该指针是一个特殊的关键字,应始终指向有效的内存块。通过查看您的使用情况,您是否可以尝试表示:
void insert(int data){
if (!next){
next = new Node(data);
}
您不能为该指针赋值,该指针是一个特殊的关键字,应始终指向有效的内存块。通过查看您的使用情况,您是否可以尝试表示:
void insert(int data){
if (!next){
next = new Node(data);
}
大概是这样的:
void insert(int data)
{
Node* newNode = new Node(data);
if (next!=NULL)
newNode->next = next;
next = newNode;
}
不能直接分配给“this”;您需要考虑的是如何表示空列表,最有可能是:
Node* head = 0;
因此,您可以通过以下方式添加第一个节点:
head = new Node(data);
大概是这样的:
void insert(int data)
{
Node* newNode = new Node(data);
if (next!=NULL)
newNode->next = next;
next = newNode;
}
不能直接分配给“this”;您需要考虑的是如何表示空列表,最有可能是:
Node* head = 0;
因此,您可以通过以下方式添加第一个节点:
head = new Node(data);
如果
此
为空
,您如何使用它的成员?这个
怎么可能是NULL
呢?下面是什么?Node*n=NULL;这是指向节点的指针。没有从该节点创建节点。那里的NULL
表示它没有指向任何东西。@user1202422:您不能在NULL指针上调用成员<代码>插入中的该
是一个节点常量*
(即不能更改)。。。你需要重新审视你的设计,考虑你想<代码>追加< /代码>一个新的<代码>节点< /代码>到一个列表…也许你错过了列表?如果我错过了:n=新节点;n、 插入(5);//在这一步中,insert不会在空节点上运行吗?如果此
为空
,您如何使用它的成员?这个
怎么可能是NULL
呢?下面是什么?Node*n=NULL;这是指向节点的指针。没有从该节点创建节点。那里的NULL
表示它没有指向任何东西。@user1202422:您不能在NULL指针上调用成员<代码>插入中的该
是一个节点常量*
(即不能更改)。。。你需要重新审视你的设计,考虑你想<代码>追加< /代码>一个新的<代码>节点< /代码>到一个列表…也许你错过了列表?如果我错过了:n=新节点;n、 插入(5);//在这一步中,insert不是在一个空节点上运行吗?如上所述,如果我有:int main(){node*n=new node;n->insert(5);//在这种情况下,我们希望该方法等效于:n->data=data,n->next=NULL。}也许您的类应该有两个函数,即setData和insert。n->setData()设置n的数据,但n->insert()设置列表中最后一个节点的数据。除此之外,您必须有一个根节点,其中包含一个要实际插入某些内容的数据。若我有:int main(){node*n=new node;n->insert(5);//在这种情况下,我们希望该方法等效于:n->data=data,n->next=NULL。}也许您的类应该有两个函数,即setData和insert。n->setData()设置n的数据,但n->insert()设置列表中最后一个节点的数据。此外,您必须有一个根节点,其中包含一个要实际插入内容的数据。