rajamit872

Implementation of Linked List in Ascending Order

Oct 25th, 2014
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<stdlib.h>
  4. void add(struct node **, int num);
  5. void display(struct node *);
  6. int count (struct node *);
  7.  
  8. struct node
  9. {
  10. int data;
  11. struct node *link;
  12. };
  13.  
  14.  
  15. void main()
  16. {
  17. struct node *p;
  18. p=NULL;
  19.  
  20. clrscr();
  21.  
  22. add(&p,5);
  23. add(&p,3);
  24. add(&p,4);
  25. add(&p,7);
  26. add(&p,0);
  27. add(&p,41);
  28. add(&p,71);
  29. add(&p,20);
  30. add(&p,434);
  31. add(&p,-7);
  32. add(&p,80);
  33.  
  34. printf("\n\nNo of Elements in the linked list %d\n\n",count(p));
  35. printf("\nElements in the linked list in the ascending fashion\n");
  36. display(p);
  37.  
  38. getch();
  39. }
  40.  
  41.  
  42.     /*add the element in the ascending order*/
  43.     void add(struct node **q, int num)
  44.     {
  45.     struct node *temp=*q,*r;
  46.  
  47.     r = (struct node*) malloc (sizeof(struct node*));
  48.     r->data = num;
  49.  
  50.     /*if the linked list is empty or
  51.     the first node is to be added at begning*/
  52.     if(*q==NULL ||(*q)->data>num)
  53.     {
  54.       *q = r;
  55.       (*q)->link = temp;
  56.     }
  57.     else
  58.     {
  59.       /*traverse the entire linked list
  60.       ti find the accurate position*/
  61.       while(temp!=NULL)
  62.       {
  63.         if(temp->data<=num  &&  (temp->link==NULL || temp->link->data>num))
  64.         {
  65.           r->link = temp->link;
  66.           temp->link = r;
  67.           return ;
  68.         }
  69.       temp = temp->link;/*go to the next node*/
  70.       }
  71.     }
  72.     }
  73.  
  74.  
  75.         /* displays the contenet of element */
  76.         void display(struct node *q)
  77.         {
  78.           /* traverse the entire linked list */
  79.           while(q!=NULL)
  80.           {
  81.            printf("%d  ", q->data);
  82.            q=q->link;
  83.           }
  84.           printf("\n");
  85.         }
  86.  
  87.  
  88.         /* counts the number of nodes present in the linked list*/
  89.            int count(struct node *q)
  90.            {
  91.          int c=0;
  92.           /* traverse the entire linked list */
  93.           while(q!=NULL)
  94.           {
  95.             q=q->link;
  96.             c++;
  97.           }
  98.           return c;
  99.            }
Advertisement
Add Comment
Please, Sign In to add comment