ordered list in C returning just one node (head overwritten)

82 views Asked by At

I'm trying to create an ordered list in C, given a specific prototype:

int insertInOrder (list_t list, char *surname, char *name);

The function should insert all nodes in the correct position (alphabetically ordered by surname first, name then - compared in function comparison) and return 1 if the insertion went through, 0 if the node is a duplicate.

comparison returns 1 if the first parameter is greater then the second, -1 if it is lesser and 0 if the two parameters are equal. I defined:

typedef struct list *list_t;

typedef struct node *link;

struct node{
    char *name;
    char *surname;
    link next;
};

struct list{
    link head;
};

This is my function:

int insertInOrder (list_t list, char *cognome, char *nome){
    link t = list->head;
    link p;

    link x = malloc(sizeof(*x));
    x->name = malloc(strlen(name)*sizeof(char));
    x->name = name;
    x->surname = malloc(strlen(surname)*sizeof(char));
    x->surname = surname;
    x->next = NULL;


    if(list->head == NULL){
        list->head = x;
        return 1;
    }
    else{
        while(t!=NULL){
            if(comparison(t,x)<0){
                p = t;
                t = t->next;
            }
            else if(comparison(t,x)>0){
                if(t == list->head){
                    x->next = list->head;
                    list->head = x;
                    return 1;
                }
                else{
                    p->next = x;
                    x->next = t;
                    return 1;
               }
            }
            else if(comparison(t,x)==0)
                return 0;
        }
        p->next = x;
        return 1;
    }
}

t is the pointer to the current node, p is the pointer to the previous one.

When I print the list, the head is overwritten (the new node replace the old one and the list appears as if it has just one node) and I can't understand why.

console result

Any suggestions?

0

There are 0 answers