我在 C++ 程序中有以下链表。我认为它构建得当。
struct Node
{
int data;
Node* next = NULL;
};
void addNode(Node *head, int data);
int main()
{
struct Node
{
int data;
Node* next = NULL;
};
Node *head = new Node;
head->data = 3;
addNode(head, 5);
system("pause");
return 0;
}
void addNode(Node *head, int data)
{
Node *curr = head;
while (curr->next != NULL)
{
curr = curr->next;
}
Node *newnode = new Node;
curr->next = newnode;
}
首先我创建了一个节点结构,然后我创建了一个 head
并将其设置为一个 new Node。
我也只是设置了 head->data = 3
。然后我调用我的 addNode
函数,该函数接受一个 Node * head
,实际上是将一个节点添加到链表的末尾。但是,当我传入 head 时,在语句 addNode(head, 5)
中,我收到一条错误消息,提示 'void addNode(Node *,int)': cannot convert argument 1 from ' main::Node *' 到 'Node *'
这是为什么?这对我来说没有意义。
最佳答案
这只是一个一般范围问题。在您的 addNode
函数中,正在使用的 struct Node
是在您的 main()
之前声明的节点。但是,main
函数中的代码在 main
范围内使用了重新定义的 struct Node
...因此出现了 错误无法将 main::Node* 转换为 Node*
。
从 main
中删除 struct Node
的定义,它应该可以工作。
此外,在您的 addNode
函数中,您没有设置新的 Node
的数据值,因此请确保也这样做。
关于类型为 "Node*"的 C++ 链表参数不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42349465/