title: Sort a Linked list using C
body: <p>I am trying to sort a Linked list, but not able to do it. Below is my code. Can anyone  help me. I have seen some programs too, which sort linked list and their approach is also like this only.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  struct node {
      int data;
      struct node *next;
  };
  
  int push(struct node **h, int x)
  {
      struct node *temp = (struct node*)malloc(sizeof(struct node));
      temp-&gt;data = x;
      temp-&gt;next = *h;
  *h = temp;
      return 0;
  }
  
  void print(struct node *head)
  {
      struct node *temp = head;
      while(temp != NULL)
      {
          printf("%d ",temp-&gt;data);
          temp = temp-&gt;next;
      }
      printf("\n");
  }
  
  void sort(struct node **h)
  {
      int i,j,a;
  
      struct node *temp1;
      struct node *temp2;
  
      for(temp1=*h;temp1!=NULL;temp1=temp1-&gt;next)
      {
          for(temp2=temp1-&gt;next;temp2!=NULL;temp2=temp2-&gt;next)
          {
              a = temp1-&gt;data;
              temp1-&gt;data = temp2-&gt;data;
              temp2-&gt;data = a;
          }
      }
  }
  
  int main()
  {
      struct node * head = NULL;
      push(&amp;head,5);
      push(&amp;head,4);
      push(&amp;head,6);
      push(&amp;head,2);
      push(&amp;head,9);
      printf("List is : ");
      print(head);
      sort(&amp;head);
      printf("after sorting list is : ");
      print(head);
      return 0;
  }
  </code></pre>
  
  <p>Below is the output which i am getting :</p>
  
  <pre><code>List is : 9 2 6 4 5 
  after sorting list is : 5 4 6 2 9
  </code></pre>