首页 文章

Bool对insert函数进行了排序,并检查列表中是否已存在int

提问于
浏览
0

我正在尝试实现一个bool函数,它接收List和Int作为参数,如果int不存在于列表中,则应该插入int并返回true;如果已经存在,则返回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;
     }



  }

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

相关问题