Thursday, 3 October 2013

Create link list in sorted order

    This is a link list which take input from user & put in list in such a way that list after each insertion remain     sorted.
    for this simply we insert each input at appropriate postion. such that data remain sorted.
    i.e if we insert data (let sey "KEY") it will inserted at postion such that data just after that is bigger than KEY & data just before key is smaller than KEY


C code ::

 // create link list in sorted order;  
 #include<stdio.h>  
 #include<malloc.h>  
 #include<stdlib.h>  
 #include<time.h>  
 clock_t begin, end;  //to compute runtime  
 double time_spent;  
 struct node     // defining structure  
 {  
      int data;  
      struct node *link;  
 }*head;  
 typedef struct node node;//using typedef to sorting name of data type  
 main()  
 {  
      begin = clock();  // starting clock to compute runtime  
      head=NULL;   //initialise head to NULL  
      int i,n,m;  
  printf("insret no of node u want\n");  
       scanf("%d",&n);   
       for(i=0;i<n;i++)  
       {  
      printf("\ninput data :");  
      scanf("%d",&m);       
      create(m);      // passing volue to insert in list  
       }  
       system ("pause"); //temprary system pouse..  
       display();     // display sorted data  
       end = clock();    // stop clock  
       time_spent = (double)(end - begin);  
       printf("\n runtime = %lf second \n",time_spent/1000000);  
       system ("pause");  
 }  
 int create(int num) //insert data in list in sorted order  
 {  
      node *temp,*r;  //declare variable of tupe struct node  
           temp=head;  
   r=(node*)malloc(sizeof(node));  
   r->data=num;  
   if(head==NULL || r->data < head->data)  
   {  
        head=r;  // r added as first node  
        head->link=temp; //r->link to old head->link  
   }  
   else  
   {  
    while(temp!=NULL)       // traverse entire link list  
    {  
         if(num >= temp->data &&(temp->link==NULL || num<temp->link->data) )  // find appropriate position to insert  
         {  
              r->link=temp->link;  
              temp->link=r;  
              return;  
         }  
         temp=temp->link; // move to next node  
    }  
   }  
 }  
 int display()   // dispaly final link list  
 {  
      node *temp;  
      if(head == NULL)  
      {  
           printf("\n empty link list\n");  
      }  
      else  
      {  
           printf("\ndata element of list :");  
           temp=head;  
           while(temp!=NULL)  
           {  
                printf(" %d ",temp->data);  
                temp=temp->link;  
           }  
      }  
 }  

OUTPUT :-

1 comment:

THANKS FOR UR GREAT COMMENT

Blogger Widgets