Advertisement
mhrabbi

Delete a node from any position of a given linked list

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