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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

deleting multiple items from a list 1

Status
Not open for further replies.

JAS19831

Programmer
Jul 31, 2005
1
US
I'm having trouble deleting multiple items from a list.
I need to ask the user how many numbers they want to delete from the top of the list, then delete them.
This is what I have got:

bool LinkedList::deleteFirstN(int N)
{
nodePtr currPtr;
for(int i = 0; i < N; i++)
{
if(N > size())
{
return false;
}
currPtr = head;
head = head->next;
currPtr->next = NULL;
delete currPtr;
}
return true;
}

this is the first time i've done this so if anyone could help I would be thankful.
 
The code looks good, but the only discrepancy that I can see is that you should make currPtr a pointer...

bool LinkedList::deleteFirstN(int N)
{
nodePtr* currPtr; // Not nodePtr currPtr;
...
}
 
You check
Code:
if ( N > size() )
for ever loop iteration, which is wasteful. Move it before the for loop.

I think the major problem you are having is because of this line:
Code:
currPtr->next = NULL;
remove that line, otherwise on your 2nd iteration, when you do:
Code:
head = head->next;
you are really doing:
Code:
head = NULL->next;  // BANG!  You're dead.
 
cpjust

You have a point with the
Code:
if (N > size)() )
comment, however the rest of what you wrote is wrong.

The pointer head is getting deleted and recreated at the start of the loop, so the second time through it is not doing as you say as it has been reinitiated.

As far as I can tell (i havn't tested the code) but it looks like Saul775 fixed the problem with the original code.

Robert Cumming
 
Doh! I must have mixed those two lines around when I looked at it. But the "currPtr->next = NULL;" still isn't required.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top