c++ - 在链表末尾插入节点时出错

标签 c++ compiler-errors singly-linked-list insertion

SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
    if(head==NULL)
    {
        SinglyLinkedListNode* tmp=new SinglyLinkedListNode();
        tmp->data=data;
        tmp->next=NULL;
        head=tmp;
        return head;
    }
    else
    {
        insertNodeAtTail(head->next,data);
    }
}

这些是编译器在编译后给出的错误。

solution.cc: In function ‘SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode*, int)’:
solution.cc:60:60: error: no matching function for call to ‘SinglyLinkedListNode::SinglyLinkedListNode()’
         SinglyLinkedListNode* tmp=new SinglyLinkedListNode();
                                                            ^
solution.cc:10:9: note: candidate: SinglyLinkedListNode::SinglyLinkedListNode(int)
         SinglyLinkedListNode(int node_data) {
         ^~~~~~~~~~~~~~~~~~~~
solution.cc:10:9: note:   candidate expects 1 argument, 0 provided
solution.cc:5:7: note: candidate: constexpr SinglyLinkedListNode::SinglyLinkedListNode(const SinglyLinkedListNode&)
 class SinglyLinkedListNode {
       ^~~~~~~~~~~~~~~~~~~~
solution.cc:5:7: note:   candidate expects 1 argument, 0 provided
solution.cc:5:7: note: candidate: constexpr SinglyLinkedListNode::SinglyLinkedListNode(SinglyLinkedListNode&&)
solution.cc:5:7: note:   candidate expects 1 argument, 0 provided
solution.cc:72:1: error: control reaches end of non-void function [-Werror=return-type]
 }
 ^

最佳答案

您没有SinglyLinkedList 的默认构造函数,但您有一个采用int 的构造函数。您也不会从 else block 中返回任何内容。

您还应该更喜欢使用 nullptr 而不是 NULL 进行指针比较。

SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
    if(head==nullptr) //Use nullptr
    {
        SinglyLinkedListNode* tmp=new SinglyLinkedListNode(data); //Construct with data
        tmp->data=data; //This line can probably be removed now?
        tmp->next=NULL;
        head=tmp;
        return head;
    }
    else
    {
        return insertNodeAtTail(head->next,data); //Make sure to return here aswell
    }
}

关于c++ - 在链表末尾插入节点时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50886162/

相关文章:

c++ - 仅在接口(interface)中包含 header ,不在实现中包含 header

c++ - 如何在没有 pstack 和 gdb 的情况下获取线程堆栈信息

c - 删除某个值多次出现的链表

javascript - 拒绝带有错误的 Promise 时出现 TypeScript 错误 TS2345

c - 我在编译这个 c 程序时遇到这些错误

java - java中的单链表

c++ - 我将如何为列表编写 pop_front 函数?

android - 以原生方式访问 mat 像素

c++ - 根据字符串获取结构元素 vector 的值

c++ - Visual Studio 2010 中是否有编译器设置以确保可移植C++ 的编写?