To delete any node from a single linked list you have the average case and one edge case. The average case is easy: loop through the list until the next node is the node you're trying to delete, and set the current node's link to the link of the node you want to delete:
while ( iter->next != 0 && iter->next->data != key )
iter = iter->next;
if ( iter->next != 0 )
iter->next = iter->next->next;
This works for deleting every node except the first because there's no node that points to it. So you need to do reset the first node to point to its link:
if ( head->data == key )
head = head->next;
else {
//...
while ( iter->next != 0 && iter->next->data != key )
iter = iter->next;
if ( iter->next != 0 )
iter->next = iter->next->next;
}
It really helps to draw this logic out on paper. What I like to do is simulate the logic with a handful of change.
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Offline 11,807 posts
since Sep 2004