Johnny Doey
Johnny Doey

Reputation: 93

Deleting node from linked list issues C

I'm simply trying to delete a node from the linked list and seem to be having trouble. I was wondering if someone could please have a look at what could be wrong? Thanks!

struct ets {
    struct node *equip_head;
    struct node *member_head;
    struct node *loan_head;

    const char *equip_fname;
    const char *member_fname;
    const char *loan_fname;
};

struct node {
    void *data; /* Accepts all data, yay */
    struct node *next;
};

BOOLEAN deleteMember(struct ets *ets, char MemberID[]) {
    struct node *current = ets->member_head;
    struct node *tmpNode = current;
    struct member_data *member_data = NULL;

    while (current != NULL) {
        member_data = current->data;

        if (strcmp(member_data->MemberID, MemberID) == 0) {
            tmpNode = current;
            current = current->next;
            free(tmpNode->data);
            free(tmpNode);

            return TRUE;
        }

        current = current->next;
    }

    return FALSE;
}

Upvotes: 0

Views: 66

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148890

As you have a single linked list you delete algorythm is broken. Here is what your are currently doing :

  • locate member to delete. Fine. You have node-1 -> node -> node+1
  • you delete the member. Why not. But you list would become node-1 -> unallocated node and no way to find next nodes

You should instead test if next node has the correct id to have something like : prev_node(current) -> node_to_delete -> next_node`

Then you can do :

tmpNode = current->next;
current->next = tmpNode->next; /* ok for the chaining */
free(tmpNode->data); /* deletion will be ok */
free(tmpNode);

With of course a special management for first and last nodes ...

Edit : Ali already gave the answer. I leave this one as a comment on why OP's algo was broken

Upvotes: 0

Ali Akber
Ali Akber

Reputation: 3800

You are not removing the node from list. You can do this to remove a node from a list:

BOOLEAN deleteMember(struct ets *ets, char MemberID[]) {
    struct node *current = ets->member_head;
    struct node *prev=NULL;
    struct member_data *member_data = NULL;


    while(current != NULL) {
        member_data = current->data;

        if(strcmp(member_data->MemberID, MemberID) == 0) {

            if(prev==NULL) // removing 1st node
                ets->member_head=current->next;
            else
                prev->next=current->next; // removing current node from list

            free(current->data);
            free(current);

            return TRUE;
        }
        prev = current;
        current = current->next;
    }

    return FALSE;
}

Upvotes: 1

Related Questions