我正在尝试实现一个接收List和Int作为参数的bool函数,如果列表中不存在int,则应插入int并返回true;如果已经存在,则返回false,我已经工作了几个小时使用此函数,并且if-else语句可以插入已排序的int,问题(和崩溃)是如何检查该值是否已存在并返回false,这是我的函数: 结构声明
typedef struct E_Type * List;
struct E_Type
{
int data;
List next = 0;
};
和功能
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;
}
}
答案 0 :(得分:1)
do{
//this line doesn't really do anything...
current->data;
//moving current forward, good.
current = current->next;
//If current->data is less than data in the list, it will exit the loop here anyway.
}while (current->data == data);
您也没有检查是否已到达列表的末尾。也许你想要做的就是这样:
//This is correct for for iterative approach, but I don't think this is really what you need, either...
while(current != null) {
if (current->data == data)
return false;
current = current->next;
}
但是,您可能不希望使用这样的迭代来在递归函数中进行此检查,因此,只需将整个位替换为:
if (current->data == data)
return false;
要通过递归调用返回正确的值,您需要更改:
else if(l->data < data){
insert(l->next, data); //Recursive call
return true; //you don't want to just return true, return what the recursive call returns!
}
要:
else if(l->data < data){
return insert(l->next, data);
}