Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- //program with linked list that delete all the nodes with value > x and value < y
- typedef struct node{
- int data;
- struct node *next;
- }node;
- void print(node *head){
- node *cursor=head;
- if(cursor==NULL)
- printf("list empty");
- while(cursor!=NULL){
- printf("%d ",cursor->data);
- cursor=cursor->next;
- }
- }
- node * fill_up_list(int n){
- int value;
- node * k=NULL;
- for(int i=1;i<=n;i++){
- node * cursor=malloc( sizeof(node) );
- scanf("%d",&value);
- cursor->data=value;
- cursor->next=k; //from last to first node
- k=cursor;
- }
- return k;
- }
- node* deletexy(node* head,int x,int y){
- node* cursor=head;
- node* tmp=head;
- //if the list has only 1 node
- if(head->next==NULL){
- //check the first node
- if (((head->data)>x)&&((head->data)<y)){
- tmp=head;
- head=head->next;
- tmp->next=NULL;
- free(tmp);}
- return head;}
- //else
- //check the middle
- while(cursor->next->next!=NULL){
- if(((cursor->next->data)>x)&&((cursor->next->data)<y)){
- tmp=cursor->next;
- cursor->next=cursor->next->next;
- tmp->next=NULL;
- free(tmp);}
- else cursor=cursor->next;
- }
- //check the last node
- cursor=head;
- while(cursor->next->next!=NULL)
- cursor=cursor->next;
- if (((cursor->next->data)>x)&&((cursor->next->data)<y)){
- tmp=cursor->next;
- cursor->next=NULL;
- free(tmp);
- }
- //check the first node
- if (((head->data)>x)&&((head->data)<y)){
- tmp=head;
- head=head->next;
- tmp->next=NULL;
- free(tmp);
- }
- return head;
- }
- int main(){
- int n,x,y;
- node * head;
- printf("how many elements will the list have ?\n");
- scanf("%d",&n);
- printf("enter x and y\n");
- scanf("%d%d",&x,&y);
- printf("enter the elements: ");
- head=fill_up_list(n);
- print(head);
- head=deletexy(head,x,y);
- printf("\n");
- print(head);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement