skk
skk

Reputation: 67

C delete linked list node

I write linked list in C

the first created node's next (node->next) is NULL

and last created node is HEAD. (reversing order)

I create 3 nodes a, b, c

and I want remove the b node

Here is my code:

struct node {
    char *name;
    void *data;
    int size;
    struct node *next;
};

typedef struct node Node;

void remove_data(Node *node, char* d_name) {
    
    while (node != NULL) {
        // remove data from heap
        
        if (strcmp(node->next->name, d_name) == 0) {
            node->next = node->next->next;
            printf("remove %s\n", node->next->name);
            printf("%s -> %s\n", node->name, node->next->name);
            free(node->next);
            break;
        } else {
            node = node->next;
        }
    }
}

and call this function remove_data(head, d_name); I predicted this program prints

remove b
a -> c

but it prints

remove b
b -> b

Why is that?

Upvotes: 1

Views: 894

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

Your function in any case does not make a sense.

First of all it ignores the name stored in the first (head) node due to the comparison

strcmp(node->next->name, d_name) == 0
       ^^^^^^^^^^^^^^^^

The function may not be called for a list that contains only one node.

After this assignment

node->next = node->next->next;

the pointer to the node that shall be deleted is lost.

Also it is unclear what these data members

    void *data;
    int size;

mean and whether you need also to free the memory pointed to by the pointer data.

The function can be declared and defined the following way as it is shown below. The function definition is based on your function definition. If it is required then you should also insert the statement

free( current->data );

before

free( current );

Here is the function definition.

int remove_data( Node **node, const char *d_name )
{
    while ( *node != NULL && strcmp( node->name, d_name ) != 0 )
    {
        node = &( *node )->next;
    }

    int success = *node != NULL;

    if ( success )
    {
        Node *current = *node;
        *node = ( *node )->next;
        free( current );
    }

    return success;
}

You have to pass a pointer to the pointer to the head node to the function when you will call the function.

That is the pointer to the head node must be passed by reference. In this case if the deleted node will be the head node then the original pointer to the head node will be updated. Otherwise the function will deal with a copy of the pointer to the head node and changing the copy will not influence on the value stored in the original pointer.

Upvotes: 1

Related Questions