Hello My problem with this code is on my 2nd else loop; i never enter it and therefore i never make new nodes for my list. can anyone help me see what i am missing?
bool List::Insert(int data)
{
Node* P = new Node;
if(P==NULL)
{
return false;
}
else
{
P ->info = data;
P ->next = NULL;
if(Head == NULL)
{
Head = P;
}
else
{
Node* lastNode;
for(lastNode = Head; lastNode ->next != NULL; lastNode = lastNode ->next)
{
lastNode ->next = P;
}
}
return true;
}
}
This:
is dead wrong. It will change the
nextpointer, for every single node currently in the list, to point to your new node. You need to only change the pointer in the last node:You may also, for efficiency, want to maintain a separate
Tailpointer (in addition to yourHead) so that you can simply replace that whole operation with:That way, you won’t have to traverse the entire list every time you want to append a new node. Your code then becomes something like (without the traversal, and with updating the tail pointer as well):
I’ll stop short of criticising the fact that your
Insertmethod doesn’t actually insert but rather appends. My near-anal-retentive nitpicking nature is unlikely to endear me to you:-)