Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | None | 0 0
  1. //Insert Node in a Sorted Order.
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. struct node
  5. {
  6.     int data;
  7.     struct node* link;
  8.  
  9. };
  10. struct node* head;
  11. void print()
  12. {
  13.     struct node* temp;
  14.     temp=head;
  15.     while(temp!=NULL)
  16.     {
  17.         printf("%d ",temp->data);
  18.         temp=temp->link;
  19.  
  20.     }
  21. }
  22. void insert(int value)
  23. {
  24.     struct node* temp1=(struct node*)malloc(sizeof (struct node));
  25.     temp1->data=value;
  26.     if(head==NULL)
  27.     {
  28.         temp1->link=head;
  29.         head=temp1;
  30.     }
  31.     if(temp1->data<head->data)
  32.     {
  33.         temp1->link=head;
  34.         head=temp1;
  35.     }
  36.     else
  37.     {
  38.         struct node* pred=head;
  39.         struct node* p=pred->link;
  40.         while(p!=NULL&&temp1->data>p->data)
  41.         {
  42.             pred=p;
  43.             printf("%d\n",p->data);
  44.             p=p->link;
  45.         }
  46.         pred->link=temp1;
  47.         temp1->link=p;
  48.     }
  49.  
  50. }
  51.  
  52.     int main()
  53.     {
  54.         head=NULL;
  55.         insert(6);
  56.         insert(7);
  57.         insert(5);
  58.         insert(9);
  59.         insert(10) ;
  60.         insert(1);
  61.         insert(3);
  62.         insert(20);
  63.         print();
  64.         return 0;
  65.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement