I was wondering if it's possible to delete a node by value in a linked list in C++ without tracking both 'previous' and 'current' nodes.
What I did is copy next node's information into current node, link current node to next next node, and delete next node.
I've attempted something like below. However, this only works if the node to delete is not the last node. I'm unable to figure out how to accommodate for the last node.
struct Node
{
int data;
Node* next;
};
void LinkedList::deleteNode(int item)
{
Node* tmpNode = m_head;
while (tmpNode != nullptr)
{
if (tmpNode->data == item)
{
if (tmpNode->next != nullptr) // not last node
{
// this works
Node* delNode = tmpNode->next;
tmpNode->data = tmpNode->next->data;
tmpNode->next = tmpNode->next->next;
delete delNode;
}
else // last node
{
// this does not work
delete tmpNode;
tmpNode = nullptr;
}
std::cout << "deleted item " << item << '\n';
return;
}
tmpNode = tmpNode->next;
}
std::cout << "delete failed: item " << item << " not found\n";
}