insertion a node after a given node

insertion a node after a given node

by Jamiul Abedin Shovon -
Number of replies: 0

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. void randominsert(int);  
  4. void create(int);  
  5. struct node  
  6. {  
  7.     int data;  
  8.     struct node *next;  
  9. };  
  10. struct node *head;  
  11. void main ()  
  12. {  
  13.     int choice,item,loc;  
  14.     do   
  15.     {  
  16.         printf("\nEnter the item which you want to insert?\n");  
  17.         scanf("%d",&item);  
  18.         if(head == NULL)  
  19.         {  
  20.             create(item);  
  21.         }  
  22.         else  
  23.         {  
  24.             randominsert(item);  
  25.         }  
  26.         printf("\nPress 0 to insert more ?\n");  
  27.         scanf("%d",&choice);  
  28.     }while(choice == 0);  
  29. }  
  30. void create(int item)  
  31. {  
  32.       
  33.         struct node *ptr = (struct node *)malloc(sizeof(struct node *));  
  34.         if(ptr == NULL)  
  35.         {  
  36.             printf("\nOVERFLOW\n");  
  37.         }  
  38.         else  
  39.         {  
  40.             ptr->data = item;  
  41.             ptr->next = head;  
  42.             head = ptr;  
  43.             printf("\nNode inserted\n");  
  44.         }  
  45. }  
  46. void randominsert(int item)  
  47.     {  
  48.         struct node *ptr = (struct node *) malloc (sizeof(struct node));  
  49.         struct node *temp;  
  50.         int i,loc;  
  51.         if(ptr == NULL)  
  52.         {  
  53.             printf("\nOVERFLOW");  
  54.         }  
  55.         else  
  56.         {  
  57.               
  58.             printf("Enter the location");  
  59.             scanf("%d",&loc);             
  60.             ptr->data = item;  
  61.             temp=head;  
  62.             for(i=0;i<loc;i++)  
  63.             {  
  64.                 temp = temp->next;  
  65.                 if(temp == NULL)  
  66.                 {  
  67.                     printf("\ncan't insert\n");  
  68.                     return;  
  69.                 }  
  70.               
  71.             }  
  72.             ptr ->next = temp ->next;   
  73.             temp ->next = ptr;   
  74.             printf("\nNode inserted");  
  75.         }  
  76.           
  77.     }