Sort Linked List in Descending

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. #include<stdlib.h>  
  4. typedef struct node{  
  5.     int data;  
  6.     struct node* next;  
  7. }node;  
  8. struct node* head;  
  9. void insert(int x)  
  10. {  
  11.     struct node* temp=NULL;  
  12.     temp=(node*)malloc(sizeof(struct node));  
  13.     temp->data=x;  
  14.     if(head==NULL)  
  15.     {  
  16.         temp->next=NULL;  
  17.         head=temp;  
  18.     }  
  19.     else  
  20.     {  
  21.         temp->next=head;  
  22.         head=temp;    
  23.           
  24.     }  
  25. }  
  26. void print()  
  27. {  
  28.     struct node* temp=head;  
  29.     while(temp !=NULL)  
  30.     {  
  31.         printf("%d",temp->data);  
  32.         temp=temp->next;  
  33.     }  
  34. }  
  35. void sortAsc()  
  36. {  
  37. struct node* temp=head;   
  38. struct node* firstval=NULL;  
  39. int val=0;  
  40. while(temp!=NULL)  
  41. {  
  42.     firstval=temp->next;  
  43.     while(firstval!=NULL)  
  44.     {  
  45.         if(temp->data<firstval->data)  
  46.         {  
  47.             val=firstval->data;  
  48.             firstval->data=temp->data;  
  49.             temp->data=val;  
  50.         }  
  51.         firstval=firstval->next;  
  52.     }  
  53.     temp=temp->next;  
  54.       
  55. }  
  56.     printf(" Sorted ");  
  57.     print();  
  58.   
  59. }  
  60. void main()  
  61. {  
  62.     insert(2);  
  63.     insert(4);  
  64.     insert(9);  
  65.     insert(8);  
  66.     print();  
  67.     sortAsc();  
  68.     getch();  
  69. }