I have a function deleteNode that receives the head of the list, and the node to be deleted. When I run this, It successfully removes the node, but it also removes everything after it. I believe it has to do with me rebuilding the list, but I can’t figure out where my logic is wrong so I could use a little help. Here is the function code:
void deleteNode(struct lnode** head, struct lnode* node) {
struct lnode* nextNode = nodeGetNext(node);
printf("word: \n%s\n",nodeGetWord(nextNode));
struct lnode* nodeToDelete = node;
*head = nodeGetNext(nodeToDelete);
printf("Head word: %s\n",nodeGetWord(*head));
free(nodeToDelete);
}
Try drawing it out… I don’t know what your functions do exactly, so this makes some assumptions based on the names, but you can get the idea.
head(red ‘h’)nodeto delete (blue ‘n’)nextNodeto the return ofnodeGetNext(node)(I assume that’s the node after the one to delete, the green ‘nn’)nodeToDelete(purple ntd) tonodeSo your code will point head at
nodeGetNext(nodeToDelete). This is actually your unused variablenextNode. Then you freenodeToDelete.I’m pretty sure this is not what you wanted to do unless you know that the node to delete is right next to head. I think a more normal algorithm would be:
With speical cases for the Head, or an empty list, etc.