Advertisement
Guest User

Untitled

a guest
Feb 24th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 KB | None | 0 0
  1. ///insert after nth position
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct node
  6. {
  7.     int data;
  8.     struct node *next;
  9. };
  10.  
  11. int main()
  12. {
  13.     struct node *prev,*head,*p;
  14.     int n,i;
  15.     scanf("%d",&n);
  16.     head=NULL;
  17.     for(i=0;i<n;i++)
  18.     {
  19.         p=(struct node*)malloc(sizeof(struct node));
  20.         scanf("%d",&p->data);
  21.         p->next=NULL;
  22.         if(head==NULL){
  23.             head=p;
  24.         }
  25.         else{
  26.             prev->next=p;
  27.         }
  28.         prev=p;
  29.     }
  30.     struct node* ptr;
  31.     ptr=head;
  32.  
  33.     int pos,dat;
  34.     printf("Enter position and data");
  35.     scanf("%d %d",&pos,&dat);
  36.     i=0;
  37.  
  38.     while(ptr!=NULL){
  39.         ++i;
  40.         if(i==pos){
  41.             p=(struct node*)malloc(sizeof(struct node));
  42.             p->data=dat;
  43.             p->next=ptr->next;
  44.             ptr->next=p;
  45.             break;
  46.         }
  47.         ptr=ptr->next;
  48.     }
  49.  
  50.     ptr=head;
  51.  
  52.     while(ptr!=NULL)
  53.     {
  54.         printf("data : %d\n",ptr->data);
  55.         ptr=ptr->next;
  56.     }
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement