0

我正在尝试实现一个接收 List 和 Int 作为参数的 bool 函数,如果 int 在列表中不存在,则应该插入 int 并返回 true,如果 int 已经存在则返回 false,我已经使用这个函数工作了几个小时,并且 if-else 语句可以插入排序的 int,问题(和崩溃)是如何检查值是否已经存在并返回 false,这是我的函数:struct 的声明

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;
     }



  }
4

1 回答 1

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);
}
于 2012-12-05T22:20:57.470 回答