SohagAbdullah

insert at nth()

Feb 18th, 2021 (edited)
476
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node
  5. {
  6.     int age;
  7.     struct node *next;
  8. } Node;
  9.  
  10. Node *head;
  11.  
  12. void insert_at_nth(int ag,int pos)
  13. {
  14.     Node *temp = head;
  15.  
  16.     Node *new_node = (Node*) malloc(sizeof(Node));
  17.     new_node->age = ag;
  18.     new_node->next = NULL;
  19.  
  20.     if(pos == 1)
  21.     {
  22.         new_node->next = head;
  23.         head = new_node;
  24.         return;
  25.     }
  26.  
  27.     pos-=2;
  28.  
  29.     while(pos--)
  30.     {
  31.         if(temp == NULL || head == NULL)
  32.         {
  33.             printf("Position is on Mars Baby!!  ('!^)\n");
  34.             return;
  35.         }
  36.         temp = temp->next;
  37.     }
  38.     if(temp == NULL || head == NULL)
  39.     {
  40.         printf("Position is on Mars Baby!!  ('!^)\n");
  41.         return;
  42.     }
  43.     new_node->next = temp->next;
  44.     temp->next = new_node;
  45. }
  46.  
  47. void print()
  48. {
  49.     Node *current = NULL;
  50.     current = head;
  51.  
  52.     while(current!=NULL)
  53.     {
  54.         printf("%d ",current->age);
  55.         current = current->next;
  56.     }
  57. }
  58.  
  59. int main()
  60. {
  61.  
  62.     int n,age,position;
  63.     printf("Enter how many nodes you want to create: ");
  64.     scanf("%d",&n);
  65.     for(int i=0;i<n;i++)
  66.     {
  67.         printf("Enter age : ");
  68.         scanf("%d",&age);
  69.         printf("Enter Position : ");
  70.         scanf("%d",&position);
  71.         insert_at_nth(age,position);
  72.     }
  73.  
  74.  
  75.  
  76.     print();
  77.  
  78.     return 0;
  79. }
  80.  
Add Comment
Please, Sign In to add comment