So I’m in a summer OO class and we need to write a function to delete a node from the middle of a linked list. I’m really close but there are a few problems. My code iterates through the linked list successfully but there is trouble actually deleting the node once the loop finds the node. Here’s my function so far:
template< class NODETYPE >
bool List< NODETYPE >::removeMiddle( NODETYPE &value, int i )
{
ListNode <NODETYPE> * tempPtr = firstPtr;
ListNode <NODETYPE> * prevPtr ;
int counter=1;
if ( isEmpty() )
return false;
if (i <= 0)
return false;
while (tempPtr != 0 && counter < i){
counter++;
if ( firstPtr == lastPtr )
firstPtr = lastPtr = 0;
else
firstPtr = firstPtr->nextPtr;
prevPtr = tempPtr;
tempPtr = tempPtr->nextPtr;
}
if (counter == i){
value = tempPtr->data; // data being removed
delete tempPtr;
}
}
return true;
RecordCounter--;
}
You forgot to change the previous node so that it no longer points to the node you delete.
You want something (largely) similar to: