【问题标题】:Bool sorted insert function with check if int already exist in list布尔排序插入函数,检查列表中是否已存在 int
【发布时间】:2012-11-23 20:38:31
【问题描述】:

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



  }

【问题讨论】:

  • 除非这是您需要自己编写所有代码的家庭作业,否则请考虑使用std::set,它已经几乎完全符合您的要求.
  • 是的,我知道设置,但这是一门课程的一种家庭作业/作业/实验室
  • 好吧 -- 看一下代码,我没有看到任何看起来像检查 next 指针是否为非空的东西,这通常是遍历链表所需要的。跨度>

标签: c++ linked-list


【解决方案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);
}

【讨论】:

  • 非常感谢,解决方案是 while-if 方法,我之前也尝试过,但可能放错了导致程序崩溃的 return false 语句。再次感谢
  • 没问题。您还应该看到 Jerry Coffin 关于检测列表末尾的终止条件的评论。我没有在这个答案中解决这个问题,但你确实需要它,因为要插入的 data 大于列表中的最后一个值。
猜你喜欢
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 2012-04-08
相关资源
最近更新 更多