Reputation: 17
void duplicates()
{
int count=0;
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp=head;
struct node *temp1=(struct node*)malloc(sizeof(struct node));
temp1=head;
while(temp!=NULL)
{
while(temp1!=NULL)
{
if(strcmp(temp->FN,temp1->FN)==0)
{
count++;
}
temp1=temp1->next;
}
if(count>1)
{
printf("DUPLICATE FOUND: %s",temp->FN);
}
count=0;
temp=temp->next;
}
}
I'm trying to find duplicates from a linked list and can't find it with my function, I have checked to see that the linked list has all the data stored with a print() function so I think the problem lies in my logic to find the duplicates. Thank You
Upvotes: 0
Views: 7946
Reputation: 8142
You've missed one crucial line from your code (or rather put it in the wrong place).
When you've looped through the inner loop, you never reset temp1
to point back to the start of the list again.
void duplicates()
{
int count=0;
struct node *temp;
struct node *temp1;
temp=head;
while(temp!=NULL)
{
temp1=head;
count=0;
while(temp1!=NULL)
{
if(strcmp(temp->FN,temp1->FN)==0)
{
count++;
}
temp1=temp1->next;
}
if(count>1)
{
printf("DUPLICATE FOUND: %s",temp->FN);
}
temp=temp->next;
}
}
You don't need to allocate memory for either temp
or temp1
as they'll be pointing at memory allocated for your list.
I've also moved the resetting of count=0
to before the inner loop as it makes sense to prepare things before the inner loop rather than resetting them afterwards.
Upvotes: 3