Hello! i keep getting an error when the compiler gets to the while loop. I want to use this function to delete a node that contains a certain element.
the struct is
1 2 3 4 5
struct NODE
{
int num;
NODE *next;
};
It says, "First-chance exception at 0x013A9540 in LLP.exe: 0xC0000005: Access violation reading location 0x00000000."
i have no idea what that means and I been stuck all day
ptr!=NULL || ptr->num!=remitem
Well, if ptr IS null, then you have to check the ptr->num, which by definition does not exist.
Try ptr!=NULL && ptr->num!=remitem
Well, for starters, your first function parameter doesn't make any sense. void removieitem(NODE *&Top, int remitem)
should probably be void removieitem(NODE *Top, int remitem)
because you're trying to pass in a pointer to the beginning of the list. What you're currently passing in is the address of the pointer to the beginning of your list.
void removieitem(NODE *&Top, int remitem)
{
NODE *ptr =NULL ,*ptr2 = NULL;
ptr = Top;
if(ptr==NULL)
cout<<"There is no list"<<endl;
else
{
if(ptr->num==remitem)
{
Top = Top->next;
ptr->next=NULL;
delete ptr;
}
else
{
ptr2 = ptr;
ptr = ptr->next;
while(ptr!=NULL && ptr->num!=remitem)
{
ptr2 = ptr;
ptr = ptr->next;
}
if(ptr==NULL)
cout<<"The element is not in the list"<<endl;
elseif(ptr->next==NULL)
{
ptr2->next = NULL;
delete ptr;
}
else
{
ptr2->next=ptr2->next->next;
ptr->next=NULL;
delete ptr;
}
}
}
}
The reason I used the '&' is because there is a chance that the node that I am removing would be in the front of the list. So if the "Top" of the list changed i would be able to pass that by reference. It's worked for my other code.