As always being this problem comes from a book's exercises. Neither I am not studying data structures, nor the book is about that. But, there is a chapter that is "Dynamic Data Structures". I've already finished this chapter.
But, I have problem with insertion. In my opinion, my function works correctly, except that it makes duplicate nodes.
I made a precaution for that but it doesn't work. Anyway, please forgive me because of my silly mistakes. OK, Here my structure types for name lists.
typedef struct name_node_s {
char name[11];
struct name_node_s *restp;
}name_node_t;
typedef struct {
name_node_t *headp;
int size;
}name_list_t;
place_first function:
name_node_t *
place_first(name_list_t *old_listp, char name[11])
{
name_list_t *new_listp, *cur_listp;
name_node_t *new_nodep, *temp_nodep;
temp_nodep = (name_node_t *)malloc(sizeof (name_node_t));
new_listp = (name_list_t *)malloc(sizeof (name_list_t));
cur_listp = (name_list_t *)malloc(sizeof (name_list_t));
new_nodep = (name_node_t *)malloc(sizeof (name_node_t));
cur_listp->headp = old_listp->headp;
temp_nodep = old_listp->headp;
new_listp = old_listp;
if ( old_listp->headp->name != name ){ // My first precaution for duplication
while(cur_listp->headp->restp != NULL && cur_listp->headp->name != name) // My second precaution for duplication
{
if (old_listp->headp == NULL){
strcpy(new_listp->headp->name, name);
new_listp->headp->restp = NULL;
}
else if (old_listp->headp->name != name) { // Third one.
strcpy(new_nodep->name, name);
new_nodep->restp = NULL;
new_listp->headp = new_nodep;
new_listp->headp->restp = temp_nodep;
++(old_listp->size);
}
cur_listp->headp = cur_listp->headp->restp;
}
}
else{
new_listp->headp = old_listp->headp;
}
return(new_listp->headp);
}
I call that function like this;
listp->headp = place_first(listp, "Mustafa");
listp->headp = place_first(listp, "Mustafa");
My output like this: __Mustafa __Mustafa __Ataturk __Ali __Eisenhower __Kennedy Thanks for advance...
Here
if ( old_listp->headp->name != name ){
you are comparing pointers, not the contents, you want
if (strcmp(old_listp->headp->name,name)){
The same applies to the other checks.