I am trying to implement one bool function that receives List and Int as arguments and should insert int and return true if the int does not exist in the list, or false if it is already there, i have been working for several hours with this function, and the if-else statements can insert sorted int, the problem (and crash) is how to check if the value already exist and return false, here is my function:
declaration of struct
typedef struct E_Type * List;
struct E_Type
{
int data;
List next = 0;
};
and function
bool insert(List & l, int data)
{
List current = l;
do{//check if the int is already in the list
current->data;
current = current->next;
//return false;
}while (current->data == data);
if (l == 0 || l->data > data){
List new_list = new E_Type;
new_list->data = data;
new_list->next = l;
l = new_list;
return true;
}
else if(l->data < data){
insert(l->next, data);
return true;
}
}
You also aren’t checking whether you have reached the end of the list. Perhaps what you are attempting to do is something like this:
However, you probably don’t want to use iteration like this to make this check in a recursive function, so instead, simply replace that whole bit with:
And to return the correct value through the recursive calls, you’ll want to change:
To: