1

I am learning C and I try to make my own function which will delete a given node from the list. I have my struct:

typedef struct list
{
   int value;
   struct list *next;
} node;

then I create the nodes {1} {2} {3} {4}, myList_ptr is the pointer to the 1st node and then I code:

deletevalue(myList_ptr, 3);

where

void deletevalue(node *ptr, int value)
{
    node *temp = ptr;

    if(temp->value == value)
    {
        ptr = ptr->next;
    }
    else
    {
        while(temp->next->value != value)
        {
            temp = temp->next;
        }

        temp->next = temp->next->next;
    }
}

If I run the above command and print the list again I will get {1} {2} {4}. However if I run this command deletevalue(myList_ptr, 1); my 1st node isn’t deleted.

NOTES

  • I know that if I put as an argument an node that doesn’t exist, my program will break.
  • Also, I know that I don't actually delete the node, but just hiding it.

To print the list I coded this:

void printlist(node *ptr)
{
    node *temp = ptr;

    printf("Print3 the list: [");
    while(temp != NULL)
    {
        printf(" %d ",temp->value);
        temp = temp->next;
    }
    printf("]\n\n");
}

1 Answer 1

3

You never update the original pointer passed to deletevalue(). After you change it you should return the new value.

node* deletevalue(node *ptr, int value)

And call it:

mylist = deletevalue(myList_ptr, 3);
Sign up to request clarification or add additional context in comments.

3 Comments

Also, don't forget to free() the memory allocated to the node being deleted.
@anishsane OP mentioned that.
Oh sorry... I missed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.