Hello,
This program has a function alterlist() which takes a node to a list and a function check() as an argument and removes all nodes that return a non-zero value from the function check()
The program works fine . I couldn't understand one thing in the function alterlist() when I try doing
link y = b;
the program gives me an error on running
if I do that I save some condition checking inside the loop since i wouldn't have to vare about where the new list starts, but it doesn't work ??????
Code:
#include<stdio.h>
#include<stdlib.h>
/* ******************************************************* */
/* This program does arithmetic operation on a linked list */
/* ******************************************************* */
typedef struct node *link;
struct node
{
int item;
link next;
};
link makelist(link x, int num);
void printlist(link x);
int check(link x);
link alterlist(link x, int check(link));
int main()
{
link x = NULL;
x = makelist(x, 5);
x = alterlist(x, check);
printlist(x);
return 0;
}
link makelist(link x, int num)
{
int i;
if(0 == num)
{
x = NULL;
return;
}
link a = malloc(sizeof *a);
x = a;
a->item = 1;
if(1 == num)
{
a->next = NULL;
return;
}
for(i = 2; i <= num; i++)
{
a->next = malloc(sizeof *a);
a = a->next;
a->item = i;
if(i == num)
{
a->next = NULL;
break;
}
}
return x;
}
void printlist(link x)
{
link b = x;
while(b != NULL)
{
printf("%d, ", b->item);
b = b->next;
}
}
int check(link x)
{
if (NULL == x)
return 0;
else
return (x->item %2);
}
link alterlist(link x, int check())
{
link a = x, b;
link y = NULL;
while(a != NULL)
{
if(0 == check(a))
{
if(a == x)
{
b = a;
y = b;
a = a->next;
}
else
{
b = a;
if(NULL == y)
y = b;
a = a->next;
}
}
else
{
if(a == x)
a = a->next;
else
{
b->next = b->next->next;
a = a->next;
}
}
}
return y;
}