Advertisement
mhrabbi

Sorting a LinkedList

Oct 19th, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. struct node
  5. {
  6.     int data;
  7.     struct node *next;
  8. }*head;
  9.  
  10. int main()
  11. {
  12.     int n;
  13.     printf("Enter total number of node: ");
  14.     scanf("%d",&n);
  15.  
  16.     createList(n);
  17.  
  18.     printf("\nList is\n ");
  19.     displaylist();
  20.  
  21.     sortlist(head);
  22.     printf("\nSorted List is:\n");
  23.     displaylist();
  24.  
  25.     return 0;
  26. }
  27. void createList(int n)
  28. {
  29.     struct node *p,*temp;
  30.     int i,data;
  31.  
  32.     temp=(struct node *)malloc(sizeof(struct node));
  33.  
  34.     printf("Enter the data of the node 1: ");
  35.     scanf("%d",&data);
  36.  
  37.     temp->data=data;
  38.     temp->next=NULL;
  39.  
  40.     p=temp;
  41.     head=temp;
  42.  
  43.     for(i=2; i<=n; i++)
  44.     {
  45.         temp=(struct node *)malloc(sizeof(struct node));
  46.  
  47.         printf("Enter the data of the %d: ",i);
  48.         scanf("%d",&data);
  49.  
  50.         temp->data=data;
  51.         temp->next=NULL;
  52.  
  53.         p->next=temp;
  54.         p=p->next;
  55.  
  56.     }
  57.  
  58. }
  59.  
  60. void displaylist()
  61. {
  62.     struct node *temp;
  63.     temp=head;
  64.  
  65.     while(temp!=NULL)
  66.     {
  67.         printf("\n%d",temp->data);
  68.         temp=temp->next;
  69.     }
  70. }
  71. void sortlist(struct node *head)
  72. {
  73.  
  74.     struct node *i,*j;
  75.     int temp;
  76.     for (i=head; i->next!=NULL; i=i->next)
  77.     {
  78.         for(j=i->next; j!=NULL; j=j->next)
  79.         {
  80.             if(i->data>j->data)
  81.             {
  82.                 temp=i->data;
  83.                 i->data=j->data;
  84.                 j->data=temp;
  85.             }
  86.         }
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement