Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Deleting items from a Linked List

Status
Not open for further replies.

chmilz

Programmer
Jan 10, 2001
94
CA
Hi,

I am currently working on a linked list program which will allow a user to add and delete items from a list. I have the "Add" function complete but I am having troubles with the delete function.. Would anyone be able to help me??? I will post my code from the "Add" function here:

bool COList::AddNodeToList(PointerToData pData)
{
bool bSuccess = true;

if(IsNodeIdInList(pData->GetId()))
{
bSuccess = false;
cerr << &quot;\nDuplicate Node ID is not allowed.&quot; << endl;
delete pData;
pData = NULL;
}
else
{
int nPriority = pData->GetPriority();

PointerToNode pNewNode = new CNode(pData);

if (!pNewNode)
{
cerr <<&quot;\nMemory Allocation failure in AddNodeToList()&quot; << endl;

bSuccess = false;

}
else
{
if(ListIsEmpty())
{
pHead = pNewNode;
pTail = pNewNode;
}
else if(nPriority < pHead->pData->GetPriority())
{
pNewNode->pNextNode = pHead;
pHead->pPreviousNode = pNewNode;
pHead = pNewNode;
}
else if (nPriority >= pTail->pData->GetPriority())
{
pNewNode->pPreviousNode = pTail;
pTail->pNextNode = pNewNode;
pTail = pNewNode;
}
else
{
pCurrent = pHead;

for(int nIndex = 0; nIndex < nNumberOfNodes; nIndex++)
{
if (nPriority >= pCurrent->pData->GetPriority()
&& nPriority < pCurrent->pNextNode->pData->GetPriority())
{
pNewNode->pPreviousNode = pCurrent->pNextNode->pPreviousNode;
pCurrent->pNextNode->pPreviousNode = pNewNode;
pNewNode->pNextNode = pCurrent->pNextNode;
pCurrent->pNextNode = pNewNode;

nIndex = nNumberOfNodes;
}
else
pCurrent = pCurrent->pNextNode;
}
}

nNumberOfNodes++;
}
}

return bSuccess;
}

Any help on how I go about deleting an item would be great. Thanks!
 
Hi chmilz
First you have to search the node to delete.
You need 2 pointers. One before the node you want to delete (pBef) and one pointing on the node to delete (pDel).
Then you say:
pBef->next = pDel->next;
delete (pDel);

Of course you have to do all the special cases, like empty list, deleting the first node or the last node (if the last node points to NULL and you are checking for NULL if you go through the list, then there is no special case for the last node)
Have fun
Martin


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top