簡體   English   中英

在鏈表末尾插入節點時出錯

[英]error while inserting a node at end of a linked list

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的默認構造SinglyLinkedList ,但是您有一個采用int的構造函數。 您也不會從else塊返回任何else

您還應該更喜歡使用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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM