c++ - 嵌套循环到尾递归

标签 c++

实现:

bool no_uniq(list_t l);
//E: Returns true if l has no elements that appear only once in l; returns false otherwise
//Ex1: (1,5,1,5,1) -> True
//Ex2: (1,5,1,1) -> False

已经实现的功能:

bool list_isEmpty(list_t list); //True if the list is empty, false otherwise
list_t list_make(); //Make an empty list
list_t list_make(int elt, list_t list); //Make a list with element elt followed by list
int list_first(list_t list); //Retrieve the first element of list
list_t list_rest(list_t list); //Retrieve all elements of list besides the first one

所以我希望能够以尾递归方式处理这个问题,但我很难思考如何将通常具有的嵌套循环转换为尾递归函数。我知道一个尾递归调用应该处理“外部”循环,一个应该处理“内部”循环,但将它们放在一起解决这个问题似乎几乎是不可能的。任何帮助将不胜感激。

最佳答案

没有看到太多的代码,我会说

bool no_uniq(const list_t& list)
{
  if(list_empty(list))
      return true;      
  return no_uniq_acc(list_first(list), list_rest(list));
}

bool no_uniq_acc(int acc, const list_t& list)
{
  if(list_empty(list))
      return true;
  const int first = list_first(list);
  if(first==acc)
    return false;
  else
    return no_uniq_acc(first, list_rest(list));
}

如果我怀疑它是 c,您可以将 const list_t& 更改为 list_t

关于c++ - 嵌套循环到尾递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13057227/

相关文章:

c++ - 是否可以在循环中多次调用 boost :asio io_service. run()?

c++ - 在Windows中用C++获取唯一的硬件标识符

c++ for循环优化问题

c++ - `std::set` 在每种情况下都会对元素进行排序吗?

javascript - 在 Node (node.js)中有效地从 Buffer 到 Buffer 进行 Base64 解码

C++ Vector 比计算几何中的 Vector 修改了两次

服务器端的 C++ TCP 套接字多次写入()在客户端被视为单次读取

c++ - Bison and doesn't name 类型错误

c++ - 当用户调整对话框大小时,如何强制Windows不要在对话框中重绘任何内容?

c++ - 对象为模板时的静态构造