My question is about removing duplicates from a linked list. But i want to do it before adding to linked list.
struct myStr{int number; mystr *next;}
void append(mystr **q,int item)
{
myStr *temp;
temp = *q;
myStr *newone;
if(*q==NULL)// There should be control of previous elements. Call of keysearch function.
{ temp = (myStr *)malloc(sizeof(myStr));
temp->number =size;
temp->next=NULL;
*q=temp;
}
else //And also here
{ temp = *q;
while(temp->next !=NULL)
{ temp=temp->next;
}
newone = (myStr *)malloc(sizeof(myStr));
newone->count = size;
newone->next=NULL;
temp->next=newone;
}
}
int keysearch (myStr *p)
{
struct myStr *temp = p;
int found = 0;
int key= p->number;
while (temp->next != NULL)
{
if(temp->number == key)
{
return 1;
//break;
}
temp = temp->next;
}
return 0;
}
My problem is in keySearch. I don’t know what is wrong? Or is there another way for doing this.
In your code, you have 2 comments where you expect to be invoking
keySearch. In fact, you only need it in 1 place – the second comment. This is because the first place is where you are creating a brand new list, so of course nothing will be in it that you need to worry about.In the second case, you want to call this
keySearchmethod. There are 3 types ofkeySearchmethods I can think of that would be useful:int keySearch(mystr *p, int value)that looks throughpforvalueand, if found, returnstrue(non-zero number)int keySearch(mystr *p)that looks throughpfor any duplicates and removes them. This would not be called on every append, though, and the implementation above suggests this is not what you are trying to do. It’s a lot more work to do this, in any event.int keySearch(mystr *p)that looks throughpto see if the first value inqis duplicated, returningtrueif it is. It seems this is what your method is trying to do.Based on the signature of the method, you are trying to do #2 or #3. But both of those are wrong-headed – they assume you’ve already added the duplicate to the list. What you should be doing instead is trying to prevent a duplicate from being added in the first place. The method as it is does not have enough information to do that, though. It needs the value of the element that has not yet been added.
I would suggest changing the method to the one in #1, and passing in the value you want to add. If it is found, return 1. In the
appendmethod, if this function evaluates to 1, don’t append anything. Otherwise append the new element.Now, when you are about to add an element, first run it by this method. If the method returns 1, leave your
appendmethod immediately – there is nothing to be done. If it returns 0, thenmallocyour new node and set it to the end of the list.EDIT: An enterprising codesmith may want to optimize slightly so that on every
appendwe don’t do 2 loops through the whole list (one forkeySearch, and then one to find the last element for actual appending). You can do this by modifyingkeySearchslightly…