The below code is giving an error, I don't have any idea why. The below function is to insert the node at the end of the linked list.
struct Node {
    int data;
    struct Node *next;
};
Node* Insert(struct Node *head,int data)
{ 
    struct Node *p;
    p=head;
    struct Node *prev;
    struct Node *temp=(struct Node*)malloc(sizeof(struct Node));
    temp->data=data;
    temp->next=NULL;
    if(head==NULL){
        head=temp;
        return head;
        //return temp;  
    }                                           ``
    while(p!=NULL){
        prev=p;
        p=p->next;
    }
    p=temp;//If we change this line to prev->next=temp .It is giving the correct result 
    return head;
}
In the above code 
if we replace the line (p=temp;) with prev->next=temp it works.
Please help me to understand the logic behind this .
Thanks in advance.
Question is from hackrank.
 
     
    