On 21 Oct 2006 14:25:40 -0700 in comp.lang.c++,
Join Bytes! wrote,
Quote:
Originally Posted by
> else if(cursor == tail_ptr)
> {
> delete cursor;
>
> --many_nodes;
> return;
> }
Then tail_ptr and cursor both contain an invalid value, the former
pointer to the deleted node. The job here is half done.
Quote:
Originally Posted by
>Why can't I use the delete cursor statement to delete the last node?
>(the cursor points to the last node) - has anybody an idea how to
>define that correctly. The specification says when the last node is
>deleted the cursor pointer should be then null again, thats why i tried
>it with delete cursor.
I think it's because your code still has a few bugs in it and
deleting nodes leaves the list messed up. Write a simple function
to dump the list content, and call it after every operation... or at
lease after every delete while that is the part you are debugging.
Simplify!
By the way, "delete cursor" does not leave cursor as NULL, but
instead the old value is now invalid. Worse, tail_ptr has the same
value and is also invalid. "Invalid" here means you cannot
legitimately even compare it with another value.
In the simple case you write
Quote:
Originally Posted by
> cursor = cursor->link();
You should let the same line do that part also when deleting the
last node; not some special case. cursor->link() is NULL, the
assignment says in that case the result should be NULL, it all
works. I DO NOT mean to copy the line; I mean to fix the program
logic.
The loop,
Quote:
Originally Posted by
> for(cursor1 = head_ptr; cursor1 != NULL; cursor1 = cursor1->link())
is unnecessary and should be eliminated. The thing needed there is
something along the lines of
if(cursor == NULL)
tail_ptr = precursor;
Have you noticed yet that the only purpose of tail_ptr is to make
your task more difficult?