I'm trying understand deleting nodes from linked lists, so I made the function Node *deleteNode(int item. Node *head) shown below. It does delete a node, but not the one I specified in my main function. If I start with a linked lsit of (1,2,3,4,5,6), it returns a list of (1,3,4,5,6). So it always deletes the 2nd node for some reason. What is the error in my deleteNode function that is causing this?
2 Answers
With linked-lists and fumbling around with the pointers and nodes, its very important that you know which pointer points to what, and whats the general layout of your linked lists. When I try to explain it to someone I often draw a painting on my whiteboard. Just draw a small diagram with some nodes and the pointers connecting them. In this way you see very fast which pointers you have to redirect to other nodes in order to remove a node from the list.
in short: With a drawing its very clear what to do and the coding isn't hard actually if you know what to do.
You need to really think over how your list operates in order to delete a node. I would definitely consider removing several pieces from your deleteNode so that it will flow smoother. Please consider the following:
Node *deleteNode(int item, Node *head){
Node * current = head, *pTemp = NULL, *pPrev = NULL;
while((current->link->info != item) && ((current -> link != NULL)) //You want to traverse the list until you find the item.
{
pPrev = current; // Assign previous pointer which is null to head of list and so on.
current = current->link // Assign current pointer to next node.
}
if (current->link-> info == item )
{
pTemp = current; // Assign temp pointer to current pointer
current = pTemp->link; // set current to next pointer
pPrev->link = current; // set previous pointer to current
free (pTemp)
}
else
{
// Did not find at all in list.
}
return head;
}
This is all generalized and on the fly, please debug your code and write on paper the structure of your list.
=is not the same as==- clctodeleteNodeyou never modifyhead. So what happens when you try to delete the head of your list? You will return the sameheadas before (the node you just deleted). You need to handle the case where you delete the head of the list. - JS1