I'm making a little program that should allow me to insert n numbers into an array. Subsequently these numbers must be inserted in a list, avoiding to insert duplicates. I think I'm close to the solution but I don't understand where I'm wrong. My idea is to insert the first element directly in the list without doing any checks, from the second element onwards, I scroll through the list of elements inserted and check if the number I am about to insert is already present, if yes I discard it otherwise I add a node to the list. Problem is, I've made some mistakes that I can't find. Can you help me?
//This is the node
struct node
{
int dato;
struct node *next;
};
int main()
{
int i,j=0,n, control=0;
int V[dmax];
struct node *p, *prec, *head, *f;
do
{
printf("type dim of array\n");
scanf("%d",&n);
}
while(n<1 || n>dmax);
loadArray(V,n);
//______________________
for(i=0; i<n; i++){
control = 0, j=0;
if(i==0){
p=malloc(sizeof(struct node));
head = p;
p->dato=V[i];
}else{
while(j<i){
f=head;
if(V[i]==f->dato){
control = 1;
j++;
//maybe break;?
}else{
f = f->next;
j++;
}
}//while
}//else
if ( control == 1)
printf("%d discarded\n", i);
else{
p=malloc(sizeof(struct node));
p->dato=V[i];
prec->next = p;
prec = p;
}
p->next=NULL;
}//for
p=head;
printf("print list\n");
while(p != NULL){
printf("%d\n",p->dato);
p = p->next;
}
}