Sep 30, 2011 at 4:11am UTC
Im doing a project and i cant figure out how to remove all the instances for a certain integer from a linked list(The list can only be trans-versed once)
can some post an example how to do this
Last edited on Sep 30, 2011 at 4:14am UTC
Sep 30, 2011 at 4:29am UTC
Let us assume something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
class LinkListNode
{
public :
int numberStored;
LinkListNode* nextNode;
LinkListNode()
{
numberStored = 0;
nextNode = NULL;
}
};
void Delete(int searchNumber)
{
LinkListNode* prevNode = listTop;
LinkListNode* currentNode = listTop;
while (currentNode != NULL)
{
if (currentNode->numberStored == searchNumber)
{
if (currentNode == listTop)
{
listTop = currentNode->nextNode;
}
else
{
prevNode->nextNode = currentNode->nextNode;
}
delete currentNode;
}
prevNode = currentNode;
currentNode = currentNode->nextNode;
} // end the while
} // end function.
Last edited on Sep 30, 2011 at 4:32am UTC
Sep 30, 2011 at 4:52am UTC
this only deletes the first instance
i want to delete all instances
such as a list: 2, 7,3,5,3,3
if 3 is selected to be removed becomes
2,7,5
Sep 30, 2011 at 6:50am UTC
sorry i Missed my own logic, it has been a while since I did this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
void Delete(int searchNumber)
{
LinkListNode* prevNode = listTop;
LinkListNode* currentNode = listTop;
while (currentNode != NULL)
{
if (currentNode->numberStored == searchNumber)
{
if (currentNode == listTop)
{
listTop = currentNode->nextNode;
delete currentNode;
prevNode = listTop;
currentNode = listTop->nextNode;
}
else
{
prevNode->nextNode = currentNode->nextNode;
delete currentNode;
currentNode = prevNode->nextNode;
}
}
else
{
prevNode = currentNode;
currentNode = currentNode->nextNode;
}
} // end the while
}
Again I apologize for my missed step it has been a while since I had to figure that out.
Last edited on Sep 30, 2011 at 6:57am UTC
Sep 30, 2011 at 7:42am UTC
Closer, but still not quite right - I think.
Consider a list where the # to be removed appears twice (or more) at the beginning of the list.
eg. 3,3,5,7,3,9 where the 3's are to be removed. I think the 2nd 3 will be missed.
Line 15 causes the new listTop to be skipped after the first deletion.
Sep 30, 2011 at 7:34pm UTC
thanks ill see how this revision works and let you know if it does it right
thanks for the help so far