title: Create a sorted linked list
body: <p>After almost 3 years, I've started relearning <code>C</code>. </p>
  
  <p>I've created a <code>Linked list</code>, and would like to extend this to creating a sorted linked list. Here is my code:</p>
  
  <pre><code>typedef struct node{
  int data;
  struct node *ptr;
  }node;
  
  node* insert(node* head, int num){
  node *temp,*prev,*next;
  temp = (node*)malloc(sizeof(node));
  temp-&gt;data = num;
  temp-&gt;ptr = '\0';
  if(head=='\0'){
      head=temp;
  }else{
      next = head;
      prev = next;
      while(next-&gt;data&lt;=num){
          prev = next;
          next = next-&gt;ptr;
      }
      if(next==NULL){
          prev-&gt;ptr = temp;
      }else{
          temp-&gt;ptr = prev-&gt;ptr;
          prev-&gt; ptr = temp;
      }
  
  }
  return head;
  }
  
  void main(){
  int num;
  node *head, *p;
  head = '\0';
  do{
      printf("Enter a number");
      scanf("%d",&amp;num);
      if(num!=0)
          head = insert(head,num);
  }while(num!=0);
  p = head;
  printf("\nThe numbers are:\n");
  while(p!='\0'){
      printf("%d ",p-&gt;data);
      p = p-&gt;ptr;
  }
  }
  </code></pre>
  
  <p>This is my idea. I traverse the list till I find a number <code>&gt;=</code> the input. I store the previous node in <code>prev</code> and <code>next</code> node contains the current value. If next is <code>null</code>, then the list is ended and the number is the highest among the list so it is to be inserted in the last place, if the number is some where in the middle then, prev node's address part is stored in temp nodes address part now temp node pointer holds address of next node.</p>
  
  <p><strong>Edit:</strong> Problem with my code is if I enter 1,2 I get error message as <code>a.exe has stopped working</code>. I am using MinGW for compiling. I am breaking the loop when user inputs 0.</p>