c++ - 我终于在链表中创建了我的添加函数,但不能在 main 中使用。 :(

标签 c++ c linked-list malloc

我终于制作了我的 func,但不能在我的 main 中使用它。编译器错误:

cannot convert Node' toNode*' for argument 1' tovoid add(Node*, Node*)'

谁能帮我解决这个错误?

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

struct Node
{
    int data;   
    struct Node *next;  
};
void add(Node* node, Node* newNode);
int main()
{ 
    struct Node *llist;
    struct Node *newNode;
    newNode->data = 13;
    llist = (Node*)malloc(sizeof(struct Node));
    llist->data = 10;
    llist->next = (Node*)malloc(sizeof(struct Node));
    llist->next->data = 15;
    llist->next->next = NULL;
    add(llist,newNode);
    printf("test\n");
    struct Node *cursor = llist;
    while (cursor != NULL) 
    {
        printf("%d\n", cursor->data);          
        cursor = cursor->next;
    } 
    system("pause");
    return 0;   
}            
void add(Node* insertafter, Node* newNode)
{
     newNode->next = insertafter->next;
     insertafter->next = newNode;
}

最佳答案

应该是void add(struct Node* node, struct Node* newNode);

:

struct Node
{
    int data;   
    struct Node *next;  
}Node;

此外,请注意,在为实际结构分配空间之前,您将值赋给了 newNode 的字段,这是一个指针:

newNode = malloc(sizeof(stuct Node));

还有一件事 - 如果这是 C 而不是 C++,您应该删除 using namespace std;

关于c++ - 我终于在链表中创建了我的添加函数,但不能在 main 中使用。 :(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6077986/

相关文章:

python - Tensorflow 为张量创建 Protobuf

c++ - 如何将动态多维数组传递给函数?

c++ - 如何读取用于 openCV 的视频文件?

c++ - 我可以使用 Boost 1.55 构建双向协程吗?

c - 在 C 中使用 free()

C - 为 char 类型数组分配内存

java - 如何将二维数组中的值复制到双向链表

c - 使用 libxml SAX 解析器处理大量嵌套元素

c - 反向单链表

java - 自定义 LinkedList 中的 addFirst()