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");
}