title: Inserting the node at the end of the linked list
body: <p>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.</p>
  
  <pre><code>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-&gt;data=data;
      temp-&gt;next=NULL;
  
      if(head==NULL){
          head=temp;
          return head;
          //return temp;  
      }                                           ``
      while(p!=NULL){
          prev=p;
          p=p-&gt;next;
      }
      p=temp;//If we change this line to prev-&gt;next=temp .It is giving the correct result 
      return head;
  }
  </code></pre>
  
  <p>In the above code 
  if we replace the line <code>(p=temp;)</code> with <code>prev-&gt;next=temp</code> it works.
  Please help me to understand the logic behind this .
  Thanks in advance.
  Question is from <a href="https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list/copy-from/13426451" rel="nofollow">hackrank</a>.</p>