Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Deleting duplicates from a linked list, whats wrong with this code

Status
Not open for further replies.

tetramethrin

Programmer
Oct 28, 2001
2
US
I have thsi code so far, It seems correct but when ran it causes an application error, saying that memory cannot be read from a certain location
Any ideas?

void delrep (node *&head)
{ node *previous = head;

for (node *head2 = head ; head2->link != NULL;head2=head2->link)
{

for (node *compare =head->link;compare ->link !=NULL; compare=compare ->link)
{

if ( compare ->data == head2->data)
{

previous->link = compare->link;

delete compare;

if(compare->link == NULL)

break;

}

previous = compare;

}

}

}
 
The problem is simple. In the outer loop, when *head2 is the last node, *compare will be equal to NULL. Thus the condition compare->link != NULL will run into problems. So going into inner loop, check if the *head2 is in the last node.

Hope this helps

raochetan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top