C++ 在链表末尾插入节点时出错
这些是编译器在编译后给出的错误C++ 在链表末尾插入节点时出错,c++,compiler-errors,singly-linked-list,insertion,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=t
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);
}
}
您没有SingleLinkedList的默认构造函数,但有一个接受int的构造函数。您也不会从else块返回任何内容 对于指针比较,您还应该更喜欢使用nullptr而不是NULL
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]
}
^
SingleLinkedListNode构造函数有一个参数。tail->next=tmp;tail=tail->next;在这两行的位置,我们可以直接写tail=tmp??tmp和tail都是节点
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
}
}