Jump to content
  • Advertisement
Sign in to follow this  
jjoi

linked list problem

This topic is 3856 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I'm trying to implement a double linked list, but I'm having some problems with the deletion of a node:
void *remove_node(node_t *lst, node_t *node)
{
	void *temp = node - > data;
	
	if(node - > previous != NULL)
		node - > previous - > next = node - > next;
	else if(node - > next != NULL)
		*lst = * node - > next;
		
	if(node - > next != NULL)
		node - > next - > previous = node - > previous;
		
	free(node);
	return temp;
}


I'm getting double frees when I consecutively delete nodes that are on the first position of the list (that is, the previous node is NULL).
Whats wrong with my code?

Thank You,
jjoi

Share this post


Link to post
Share on other sites
Advertisement
The code breaks in the case where you handle deleting the head of the list. When you try to readjust the head pointer, you are modifying a local copy of the head pointer.

The following should work. I have also taken the courtesy of re-writing the code with clearer logic:


void remove_node(node_t** headOfList, node_t* nodeToDelete )
{
if(nodeToDelete == *headOfList)
{
*headOfList = noteToDelete->next;
}

if(nodeToDelete->previous != NULL)
{
nodeToDelete->previous->next = nodeToDelete->next;
}

if(nodeToDelete->next != NULL)
{
nodeToDelete->next->previous = nodeToDelete->previous;
}

free(nodeToDelete);
}





Notice the type of the first argument is node_t**, thats where your previous code breaks down.

Share this post


Link to post
Share on other sites
Quote:
Original post by fpsgamer
The code breaks in the case where you handle deleting the head of the list. When you try to readjust the head pointer, you are modifying a local copy of the head pointer.

The following should work. I have also taken the courtesy of re-writing the code with clearer logic:

*** Source Snippet Removed ***

Notice the type of the first argument is node_t**, thats where your previous code breaks down.


That makes sense!
Problem solved!
Thanks! :D

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!