I'm supposed to define a function that removes all nodes with a specified value from a linked list.

I have to use this structure:

typedef struct LIST
{
	int Object;
	struct LIST *Next;
} LIST;

and here is the function I wrote

void LDeleteElem(LIST **List, int Elem)
{
	LIST* Curr = *List;
	LIST* Prev = NULL;

	while (Curr != NULL)
	{
		if (Curr->Object == Elem) /*found the node*/
		{
			if (Prev == NULL)
				*List = Curr->Next; /*if found at the beginning*/
			else
				Prev->Next = Curr->Next; /*if found anywhere else*/
			free(Curr);
		}
		Prev = Curr; Curr = Curr->Next;
	}
}

And it crashes... If I add return; after free(Curr); it works fine and removes the first node with the value of Elem it finds, but I need to remove all of them, what am I doing wrong?

Recommended Answers

All 2 Replies

This might be your problem...

On line 14 your freeing Curr and then on line 16 you set Prev to Curr...Prev now equals NULL.

Indeed, thank you! Ended up implementing it this way

void LDeleteElem(LIST **List, int Elem)
{
	LIST* Curr = *List;
	LIST* Prev = NULL;

	while (Curr != NULL)
	{
		if (Curr->Object == Elem)
		{
			if (Prev == NULL)			
				*List = Curr->Next;
			else						
				Prev->Next = Curr->Next;
			
			LIST* temp = Curr;
			Curr = Curr->Next;
			free(temp);
		}
		else 
		{
			Prev = Curr; Curr = Curr->Next;
		}
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.