Insertion and match function in linked list

Viewed 30

What seems to be the problem with the function insert here? I can't get my head head around it.

It should be a simple insert function in a linked list data structure, where the variables need to get copied over to memory allocated and if there no errors it should return 0.

int insert(char *s, char *p, char *o) {
    struct node *new = (struct node *) malloc(sizeof(struct node));
    new->Subject = s;
    new->Predicate = p;
    new->Object = o;
    struct node *temp = head;

    while (temp->next != NULL ) {
        if (strcmp(temp->next->Subject, s) > 0) {
            break;
        } else if (strcmp(temp->next->Subject, s) == 0) {
            if (strcmp(temp->next->Predicate, p) > 0) {
                break;
            } else if (strcmp(temp->next->Predicate, p) == 0) {
                if (strcmp(temp->next->Object, o) > 0) {
                    break;
                } else if (strcmp(temp->next->Object, o) == 0) {
                    return 1;
                }
            }
        }
        temp = temp->next;
    }
    new->next = temp->next;
    temp->next = new;
    return 0;
}

1 Answers

temp->next is still null or garbage value
use :

new->next = temp
Related