Monday, August 18, 2008

Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?

/*
- Copy the contents of the node following the node that is provided to the provided node.
- Delete the node following the provided node.

Solution doesn't work if the node that is provided is the last node of the singly-linked list.
*/

bool DeleteNode(NODE *pNode)
{
if ( (NULL == pNode) || (NULL == pNode->pNext) ) //make sure it is not the last node
return false;

NODE *pNext = pNode->pNext;

//Copy contents
pNode->nValue = pNext->nValue;
pNode->pNext = pNext->pNext;

//Delete
free(pNext);

return true;
}

0 comments: