I am using a linked list to make a to do list. I am having trouble with by Delete function in my implementation. The delete function is being passed a string data of the node i want to delete from the list. This function should find the item in the list and then delete the node but not creating a memory leak in the process. So if i delete an item from the middle of the list, I can still see the whole list when I print out the list.
bool List::Delete(string data)
{
Node *temp = new Node;
temp->data = data;
trailer = NULL;
cur = head;
while (cur != temp)
{
trailer = cur;
cur = cur->next;
}
trailer->next = cur->next;
if (cur->next == NULL)
{
trailer->next == NULL;
bool List::Delete(string data)
{
Node *temp = new Node; //¿? You want to remove a node, ¿why are you creating another then?
temp->data = data;
trailer = NULL; //limit the scope of your variables. I don't see any good reason for them to be members of the class
cur = head;
while (cur != temp) //tautology
{
trailer = cur;
cur = cur->next;
}
trailer->next = cur->next;
if (cur->next == NULL)
{
trailer->next == NULL; //read the warnings (enable the warnings)
}
delete temp;
if (temp) //`delete' would not set the pointer to null, tautology
{
returnfalse;
}
else
{
returntrue;
}
}
> The text file that is used
you kind of forgot the code that uses that file
If your Node had a constructor, it would remove all that initialization code.
new will never return null, so all that code that handles it will never be called. A modern compiler really should warn about it, but they don't.
List constructor doesn't initialize all its members. As ne555 said, you don't need all those members, just head as you have a single threaded linked list.
As looking up a node is possibly a common thing, you'd simplify your code if you had a private method Node* Find(const std::string& s) const, that did the lookup.
Delete would then be:
1 2 3 4 5 6 7 8 9 10
bool List::Delete(const std::string& data)
{
if (Node* p = Find(data))
{
/* delete the node */
returntrue;
}
returnfalse;
}
Pass strings by const ref rather than by value. You're creating unnecessary copies.