title: C - Inserting into linked list in ascending order
body: <p>I am trying to create a program that inserts numbers into a linked list in ascending order. This is my insert function. It works for inserting some numbers but not others. I think it has something to do with the last part, but i cant figure it out.</p>
  
  <pre><code>node* insert(node* head, int value) {
  
      //check if head hasn't been created
      if (head == NULL) {
          head = malloc(sizeof(node));
          if(head == NULL) {
              printf("Failed to create head node");
              return head;
          }
          head-&gt;value = value;
          head-&gt;next = NULL;
          return head;
      }
  
      //create a new node
      node *newNode;
      newNode = malloc(sizeof(node));
      if(newNode == NULL) {
          printf("Failed to create node");
          return newNode;
      }
      newNode-&gt;value = value;
      newNode-&gt;next = NULL;
  
      //see if new node should be placed before head
      if (value &lt; head-&gt;value) {
          newNode-&gt;next = head;
          return newNode;
      }
  
      //search through to find correct spot and insert the node
      node *temp = NULL;
      temp = head;
      while(temp-&gt;next != NULL &amp;&amp; temp-&gt;value &lt; value) {
          temp = temp-&gt;next;
      }
      newNode-&gt;next = temp-&gt;next;
      temp-&gt;next = newNode;
      return head;
  
  }
  </code></pre>