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 keySearch
method. There are 3 types of keySearch
methods I can think of that would be useful:
- Invoke a method
int keySearch(mystr *p, int value)
that looks through p
for value
and, if found, returns true
(non-zero number)
- Invoke a method
int keySearch(mystr *p)
that looks through p
for 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.
- Invoke a method
int keySearch(mystr *p)
that looks through p
to see if the first value in q
is duplicated, returning true
if 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 append
method, if this function evaluates to 1, don't append anything. Otherwise append the new element.
int keysearch(struct myStr *p, int value)
{
if(p == NULL) return 0;
// reusing p is fine - it's a local variable
while(p != NULL)
{
if(p->number == value) return 1; // return if value exists already
p = p->next; // go to next element
}
return 0;
}
Now, when you are about to add an element, first run it by this method. If the method returns 1, leave your append
method immediately - there is nothing to be done. If it returns 0, then malloc
your new node and set it to the end of the list.
EDIT: An enterprising codesmith may want to optimize slightly so that on every append
we don't do 2 loops through the whole list (one for keySearch
, and then one to find the last element for actual appending). You can do this by modifying keySearch
slightly...
// returns NULL if p is empty / value exists; otherwise returns the last element
struct myStr *keysearch(struct myStr *p, int value)
{
// same logic, different return values; integration into append changes too!
}