mhdew

Delete by position

Mar 3rd, 2018
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct NODE
  5. {
  6.     int data;
  7.     struct NODE *next;
  8. } node;
  9.  
  10. node *head;
  11.  
  12. void del(int pos)
  13. {
  14.     node *current=head;
  15.     node *prev;
  16.     int count=1;
  17.     if(pos==1){
  18.         head=head->next;
  19.         free(current);
  20.     }
  21.     else{
  22.         while(count<pos){
  23.             prev=current;
  24.             current=current->next;
  25.             count++;
  26.         }
  27.         prev->next=current->next;
  28.         free(current);
  29.     }
  30. }
  31.  
  32. int main()
  33. {
  34.     head=(node *)malloc(sizeof(node));
  35.     head->data=3;
  36.     head->next=(node *)malloc(sizeof(node));
  37.     head->next->data=6;
  38.     head->next->next=(node *)malloc(sizeof(node));
  39.     head->next->next->data=2;
  40.     head->next->next->next=(node *)malloc(sizeof(node));
  41.     head->next->next->next->data=7;
  42.     head->next->next->next->next=NULL;
  43.  
  44.     del(2);
  45.  
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment