Search code examples
c++compiler-errorssingly-linked-listinsertion

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);
    }
}

these are the errors which the compiler is giving after compilation.

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]
 }
 ^

Solution

  • You don't have a default constructor for SinglyLinkedList, but you have a constructor that takes an int. You are also not returning anything from your else block.

    You should also prefer to use nullptr instead of NULL for pointer comparison.

    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
        }
    }