I'm trying to eliminate all the occurrences of repeated elements in a linked list. For example, if I have: 1-2-3-2-4-2-4, I want to eliminate all the occurrences of 2 and 4 and get: 1-3
I use a function called eliminateRepeated
that iterates and counts the occurrences; if the count is bigger than 1, the program calls the function eliminateAllTheOc
. But I get this:1-3-2-4. The last occurrence is not eliminated.
If I call the function eliminateAllOc
separately with the value 4 for example, it works fine and returns 1-2-3-2-2.
typedef struct{
int num;
}t_dataL;
typedef struct s_nodeL{
t_dataL dataL;
struct s_nodeL *next;
}t_nodeL;
typedef t_nodeL *t_list;
int elimnateAllTheOc(t_list *l, t_dataL *d, int(*cmp)(const void*, const void*)){
if(!*l) return 0;
t_nodeL *aux;
while(*l){
if(cmp(&(*l)->dataL, d) == 0){
aux = *l;
*l = (*l)->next;
free(aux);
}
else l = &(*l)->next;
}
return 1;
}
int eliminateRepeated(t_list *l, int(*cmp)(const void*, const void*)){
t_list *plec, *ini = l;
t_nodeL *aux;
int n = 0;
while (*l){
plec = ini;
while(*plec){
if(cmp(&(*l)->dataL, &(*plec)->dataL) == 0) n++;
plec = &(*plec)->next;
}
if(n > 1) eliminateAllTheOc(ini, &(*l)->dataL, cmp);
else l = &(*l)->next;
n = 0;
}
return 1;
}
How can I eliminate all occurrences of a repeated element?