ShadowedKitty
Coder
So I am relatively new to C++ and coding in general, and have an assignment that requires me to have minimal memory leakage. I get the general idea, but I do not understand where to put the different delete commands. If someone could help me on where to put delete commands for this insert function for a sorted single linked list, I could figure it out from there. Thanks
[CODE title="Insert"]bool LList::Insert(InfoType* x_ptr)
{
Node* n = new Node(x_ptr, list);
if (IsEmpty())//if true, starts a new list
{
list = n;
return true;
}
else//if list already started
{
if (*list->infoPtr == *x_ptr)//if true, first element is equal to new element
{
return false;
}
else if (*x_ptr < *list->infoPtr)//if true, first element comes after new element
{
list = n;
return true;
}
else //if here, first element comes before new element
{
Node* current = list;
while (current->next != NULL && *current->next->infoPtr < *x_ptr)//if true, current->next exists and comes before new element
current = current->next;
if (current->next != NULL && *current->next->infoPtr == *x_ptr)// if true, element already exists
{
return false;
}
else {//if here, add a new element in found location
Node* w = new Node(x_ptr, current->next);
current->next = w;
return true;
}
}
}
}[/CODE]
[CODE title="Insert"]bool LList::Insert(InfoType* x_ptr)
{
Node* n = new Node(x_ptr, list);
if (IsEmpty())//if true, starts a new list
{
list = n;
return true;
}
else//if list already started
{
if (*list->infoPtr == *x_ptr)//if true, first element is equal to new element
{
return false;
}
else if (*x_ptr < *list->infoPtr)//if true, first element comes after new element
{
list = n;
return true;
}
else //if here, first element comes before new element
{
Node* current = list;
while (current->next != NULL && *current->next->infoPtr < *x_ptr)//if true, current->next exists and comes before new element
current = current->next;
if (current->next != NULL && *current->next->infoPtr == *x_ptr)// if true, element already exists
{
return false;
}
else {//if here, add a new element in found location
Node* w = new Node(x_ptr, current->next);
current->next = w;
return true;
}
}
}
}[/CODE]