The immediate problem is line 90 which should be
delete target;
If you think about it, at this point in the code you are using variable
Delete
as the pointer to the previous node in the list.
target
is the node to delete. If you'd created a separate variable like prev, the code would probably be clearer and you might have avoided the mistake. The point here is that clear variable names are important:
1 2 3 4 5 6 7 8 9 10 11 12
|
Node *prev = start;
while ((prev->next != NULL) && (!(item==prev->next->data)))
{
prev = prev->next;
}
Delete = prev->next;
if (Delete != NULL)
{
prev->next = Delete->next;
delete Delete;
length--;
}
|
Personally, I think it's clearer to use a "current" and "previous" pointer, and do the work inside the loop:
1 2 3 4 5 6 7 8 9
|
Node *cur;
for (Node *prev = start; cur = prev->next; prev = cur) {
if (cur->data == item) {
prev->next = cur->next;
delete cur;
length--;
break;
}
}
|
Also, it's never a good idea to put a
using namespace
statement in a header file because that bleeds into every other header file that might be included after the the current one. So move line 7 of UnsortedList.h to line 3 of Unsortedlist.cpp.
But the best way to delete from a linked list is to use a variable that points to
start
or the
next
pointer. All of the special cases disappear and the entire delete function becomes just a few lines:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void
unsortedList::DeleteItem(int item)
{
Node **pStartOrNext, *cur;
for (pStartOrNext = &start;
(cur = *pStartOrNext);
pStartOrNext = &cur->next) {
if (cur->data == item) {
*pStartOrNext = cur->next;
delete cur;
length--;
break;
}
}
}
|