Advertisement
mhrabbi

Insert a node (both before&after) a given number in a list

Oct 17th, 2019
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.74 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<malloc.h>
  3. #include<stdlib.h>
  4.  
  5. struct node
  6. {
  7.     int data;
  8.     struct node *next;
  9. }*head;
  10.  
  11.  
  12. int main()
  13. {
  14.     int n,m,data;
  15.     printf("Enter total number of node: ");
  16.     scanf("%d",&n);
  17.  
  18.     createList(n);
  19.  
  20.     printf("\nList is\n ");
  21.  
  22.     displaylist();
  23.  
  24.     printf ("\n\nEnter data to insert at beginning of the list: ");
  25.     scanf ("%d",&data);
  26.     AddAtBeg(data);
  27.  
  28.     displaylist();
  29.  
  30.     printf ("\n\nEnter data to insert at end of the list: ");
  31.     scanf ("%d",&m);
  32.     AddAtEnd(m);
  33.  
  34.     displaylist();
  35.  
  36.     return 0;
  37. }
  38. void createList(int n)
  39. {
  40.     struct node *p,*temp;
  41.     int i,data;
  42.  
  43.     temp=(struct node *)malloc(sizeof(struct node));
  44.  
  45.     printf("\nEnter the data of the node 1: ");
  46.     scanf("%d",&data);
  47.  
  48.     temp->data=data;
  49.     temp->next=NULL;
  50.  
  51.     p=temp;
  52.     head=temp;
  53.  
  54.     for(i=2; i<=n; i++)
  55.     {
  56.         temp=(struct node *)malloc(sizeof(struct node));
  57.  
  58.         printf("Enter the data of the node %d: ",i);
  59.         scanf("%d",&data);
  60.  
  61.         temp->data=data;
  62.         temp->next=NULL;
  63.  
  64.         p->next=temp;
  65.         p=p->next;
  66.  
  67.     }
  68.  
  69. }
  70.  
  71. void displaylist()
  72. {
  73.     struct node *temp;
  74.     temp=head;
  75.  
  76.     while(temp!=NULL)
  77.     {
  78.         printf("\n%d",temp->data);
  79.         temp=temp->next;
  80.     }
  81. }
  82. void AddAtEnd(int data)
  83. {
  84.     struct node *newNode, *temp;
  85.  
  86.     newNode = (struct node*)malloc(sizeof(struct node));
  87.  
  88.     newNode->data = data;
  89.     newNode->next = NULL;
  90.  
  91.     temp = head;
  92.  
  93.     while(temp->next != NULL)
  94.         temp = temp->next;
  95.  
  96.     temp->next = newNode;
  97.  
  98. }
  99. void AddAtBeg(int data)
  100. {
  101.     struct node *tmp;
  102.     tmp=(struct node*)malloc(sizeof(struct node));
  103.     tmp->data=data;
  104.     tmp->next=head;
  105.     head=tmp;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement