Your implementation is all wrong.
For one thing, you are new
‘ing temporary Node
objects that you shouldn’t be allocating at all, and you are leaking them.
And, you are not actually outputting the value of the Node
that you delete.
And, your whole function can be made much simpler, as you don’t need to enumerate the whole list at all. You already know the last Node
in the list since you have a tail
pointer directly to it, so use that pointer to access the last Node
directly (you should NOT be using a non-null sentry for the tail
– if you are, you are making things harder on yourself).
Try this instead:
bool List::getBack(int & key)
{
if (!tail)
return false;
key = tail->key; // or whatever the actual field name is ...
Node *temp = tail;
tail = tail->prev;
if (tail)
tail->next = nullptr;
else
head = nullptr;
delete temp;
return true;
}
1
solved Returning true if successful in deleting the node in C++