Sign in to follow this  

linked list problem

This topic is 3663 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
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

This topic is 3663 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this