Advertisement
Guest User

mylinkedlist

a guest
Jun 23rd, 2018
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //program with linked list that delete all the nodes with value > x and value < y
  4.  
  5. typedef struct node{
  6.     int data;
  7.     struct node *next;
  8. }node;
  9.  
  10. void print(node *head){
  11.     node *cursor=head;
  12.     if(cursor==NULL)
  13.     printf("list empty");
  14.     while(cursor!=NULL){
  15.         printf("%d ",cursor->data);
  16.         cursor=cursor->next;
  17.     }  
  18. }
  19.  
  20. node * fill_up_list(int n){
  21.  int value;
  22.  node * k=NULL;
  23.  for(int i=1;i<=n;i++){
  24.  node * cursor=malloc( sizeof(node) );
  25.  scanf("%d",&value);
  26.  cursor->data=value;
  27.  cursor->next=k;         //from last to first node
  28.  k=cursor;
  29.  }
  30.  return k;
  31. }
  32.  
  33. node* deletexy(node* head,int x,int y){
  34.     node* cursor=head;
  35.     node* tmp=head;
  36. //if the list has only 1 node
  37.     if(head->next==NULL){
  38.   //check the first node
  39.     if (((head->data)>x)&&((head->data)<y)){
  40.     tmp=head;
  41.     head=head->next;
  42.     tmp->next=NULL;
  43.     free(tmp);}
  44.    
  45.     return head;}
  46. //else 
  47.     //check the middle
  48.     while(cursor->next->next!=NULL){
  49.         if(((cursor->next->data)>x)&&((cursor->next->data)<y)){
  50.         tmp=cursor->next;
  51.         cursor->next=cursor->next->next;
  52.         tmp->next=NULL;
  53.         free(tmp);}
  54.         else cursor=cursor->next;
  55.     }
  56.    
  57.     //check the last node
  58.     cursor=head;
  59.    while(cursor->next->next!=NULL)
  60.       cursor=cursor->next;
  61.    if (((cursor->next->data)>x)&&((cursor->next->data)<y)){
  62.     tmp=cursor->next;
  63.     cursor->next=NULL;
  64.     free(tmp);
  65. }
  66. //check the first node
  67.     if (((head->data)>x)&&((head->data)<y)){
  68.     tmp=head;
  69.     head=head->next;
  70.     tmp->next=NULL;
  71.     free(tmp);
  72. }
  73.     return head;
  74. }
  75.  
  76.  
  77. int main(){
  78. int n,x,y;
  79. node * head;
  80.  
  81. printf("how many elements will the list have ?\n");
  82. scanf("%d",&n);
  83. printf("enter x and y\n");
  84. scanf("%d%d",&x,&y);
  85. printf("enter the elements: ");
  86. head=fill_up_list(n);
  87.     print(head);
  88.     head=deletexy(head,x,y);
  89.     printf("\n");
  90.     print(head);
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement