-
February 15th, 2012, 01:48 PM
#1
How to delete all values in the linked list
Hello.
I have made this program for linked list, but i have one problem with it. I want to make a function that will delete all same values I inuput in the list.
Example: if user inputs 5 I want to delete all 5 for the list.
I have tried doing this with the loop inside regular function that erase single value.
This is funnction that erases single value:
Code:
void list::Delete (int a)
{
node *temp=head;
if (temp==NULL)
return ;
if (temp->getNext()==NULL)
{
delete temp;
head=NULL;
}
else
{
node *prev;
do
{
if (temp->getBroj()==a)
break;
prev=temp;
temp=temp->getNext();
}while (temp!=NULL);
prev->setNext(temp->getNext());
}
}
This is my attempt to make function:
Code:
else
{
bool change=false;
node *prev;
do
{
change=false;
do
{
if (temp->getBroj()==a)
{
change=true;
break;
}
prev=temp;
temp=temp->getNext();
}while (temp!=NULL);
prev->setNext(temp->getNext());
}while (!change);
}
Thank you
Last edited by depecheSoul; February 15th, 2012 at 01:54 PM.
-
February 15th, 2012, 02:25 PM
#2
Re: How to delete all values in the linked list
You have problems with your initial function. Let's address them first.
Code:
if (temp->getNext()==NULL)
{
delete temp;
head=NULL;
}
What if the list contains only one node, but that node does not hold the same value as a?
Code:
}while (temp!=NULL);
prev->setNext(temp->getNext());
First, if you continue the inner loop until temp is NULL, then what do you expect to be the result of accessing temp->getNext()?
Second, what happens to the memory of the node at temp when you do this?
What if the value a is never found in the list, or is found multiple times?
By the way, for reference, here is code to do the exact same thing using the Standard Template Library.
Code:
std::list<int> mylist;
// insert some stuff into mylist
// now I want to delete all nodes containing 5
mylist.erase(std::remove(mylist.begin(),mylist.end(),5), mylist.end());
-
February 15th, 2012, 04:28 PM
#3
Re: How to delete all values in the linked list
Lindley thank you very much.
-
February 15th, 2012, 04:39 PM
#4
Re: How to delete all values in the linked list
One additional thing: What if the item to be removed is the first one in the list, but not the *only* one in the list?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|