title: Quick_Sort in Single Linked List
body: <p>I am trying to apply quick sort on a single linked list.I have created the partition function which works by considering the first element as pivot:</p>
  
  <pre><code>list-&gt;19-&gt;8-17-&gt;15-&gt;25-&gt;41
  After calling partition(&amp;list) we get :
  list-&gt;16-&gt;17-&gt;8-&gt;19-&gt;25-&gt;41
  </code></pre>
  
  <p>This is what I am trying to do :</p>
  
  <p>1.)I call Quicksort() on list->19->8-17->15->25->41</p>
  
  <p>2.)In QuickSort , We call the partition on list and so I get list->16->17->8->19->25->41 and here 'q' points to the pivot element.</p>
  
  <p>3.)Now using q we split the list in 2 parts : list1->16->17->8->Null and list2->25->41 and then call quicksort on list1 and list 2</p>
  
  <p>4.)Then I join both the lists with 'q'.</p>
  
  <p>But my program crashes in windows probably due to segmentation fault.Can someone please help me out here .</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  struct node{
      int data;
      struct node * next;
  };
  
  typedef struct node Node;
  
  void display(Node *p){
      while(p!=NULL){
          printf("%d ",p-&gt;data);
          p=p-&gt;next;
      }
      printf("\n");
  }
  
  Node * create(int d){
      Node *p=(Node *)malloc(sizeof(Node));
      p-&gt;data=d;
      p-&gt;next=NULL;
      return p ;
  }
  
  Node * partition(Node **head){
      Node *list=*head;
      Node *pv=*head;
      int pivot=list-&gt;data;
      Node *p=list-&gt;next;
      Node *temp,*q=list;
  
      while(1){
          if(!p)
              break;
  
          if(p-&gt;data&lt;pivot){
              temp=p;
              q-&gt;next=temp-&gt;next;
              p=p-&gt;next;
              temp-&gt;next=list;
              list=temp;
          }
          else{
              q=p;
              p=p-&gt;next;
          }
      }
      *head=list;
      return pv ;
  }
  
  Node * quicksort(Node * list){
  
  
  
      if(list==NULL || (list)-&gt;next==NULL)
          return list;
      Node * q,*list1,*list2,* temp;
      q=partition(&amp;list);
  
      list1=list;
  
      list2=q-&gt;next;
      temp=list1;
  
      while(1){
          if(temp-&gt;next==q)
          {
              temp-&gt;next=NULL;
              break;
  
          }
          temp=temp-&gt;next;
  
      }
  
      list1=quicksort(list1);
      list2=quicksort(list2);
      temp=list1;
      while(temp-&gt;next!=NULL)
          temp=temp-&gt;next;
      temp-&gt;next=q;
      q-&gt;next=list2;
      return list1;
  }
  
  
  
  
  
  int main(){
  
      Node *list1=create(19),*list2;
      Node *a=create(8);
      Node *b=create(17);
      Node *c=create(16);
      Node *d=create(25);
      Node *e=create(41);
      list1-&gt;next=a;a-&gt;next=b;b-&gt;next=c;c-&gt;next=d;d-&gt;next=e;
  
      list1=quicksort(list1);
      display(list1);
  
  
  }
  </code></pre>