what is the error

J

jw

//a single link list,the nodes contain an integer value called value
void handler::delete(){
int del;
cout<<"which number do u want to delete"<<endl;
cin>>del;
node *previous;//always behind the sth node

for(node *sth=head;sth!=NULL;sth=sth->next){
if(sth->value==del)
{
if(sth==head)
{
node *deleted=head;
head=head->next;
delete deleted;
}

else
{
node *deleted=sth;
previous->next=deleted->next;
delete deleted;
}
previous=sth;
}
}



}
 
V

Victor Bazarov

jw said:
//a single link list,the nodes contain an integer value called value
void handler::delete(){
int del;
cout<<"which number do u want to delete"<<endl;
cin>>del;
node *previous;//always behind the sth node

for(node *sth=head;sth!=NULL;sth=sth->next){

Drop the last statement in the parentheses:

for (node *sth = head; sth != NULL;) {
if(sth->value==del)
{
if(sth==head)
{
node *deleted=head;
head=head->next;
delete deleted;

If you want to delete all elements with value 'del', then you should stay
here and make sure you check all elements that can become heads:

sth = head;
continue;

If you only want to delete the very first one, you should bail out:

break;
}

else
{
node *deleted=sth;
previous->next=deleted->next;
delete deleted;

Same question: do you want to continue looking for value 'del'? Decide,
and then add the necessary things here.
}
previous=sth;

Add
sth = previous->next;

V
 
J

jw

Victor said:
Drop the last statement in the parentheses:
i want to delete a node whose value is del so..
for (node *sth = head; sth != NULL;) {
this statement searches the list the node which ll be deleted might be
at the head or somewhere else
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top