Inserting node at the end of linkedlist in C++

61 views Asked by At

Below is code for inserting a node at the end of a linked list. I am getting a segmentation fault. Please help!!

Node* Insert(Node *head,int data)
{
    struct Node *last=head;

    struct Node* n=(struct Node*)malloc(sizeof(struct Node));


    n->data=data;
    n->next=NULL;

    if(head==NULL)
    {
        head=n;
    }

    while(last->next!=NULL)
    {
        last=last->next;
    }

    last->next=n;
    return 0;
}
1

There are 1 answers

2
AudioBubble On

Your function is returning the numeric literal 0, but its return type is "Node *", so as soon as you try to use the return value of the function, you're headed for trouble.
What did you intend to return? The head of the modified list? Or the newly-appended Node? Either way, it's not returning them.