在 C++ 中获取反向列表
get reverse list in c++
我正在为我的大学做作业。我需要创建递归函数。
我的list_t界面包含以下功能:
List Interface
The file recursive.h defines the type "list_t" and the following operations on lists:
// EFFECTS: returns true if list is empty, false otherwise
bool list_isEmpty (const list_t& list);
// EFFECTS: returns an empty list.
list_t list_make ();
// EFFECTS: given the list (list) make a new list consisting of
// the new element followed by the elements of the
// original list.
list_t list_make (int elt, const list_t& list);
// REQUIRES: list is not empty
// EFFECTS: returns the first element of list
int list_first (const list_t& list);
// REQUIRES: list is not empty
// EFFECTS: returns the list containing all but the first element of list
list_t list_rest (const list_t& list);
// MODIFIES: cout
// EFFECTS: prints list to cout.
void list_print (const list_t& list);
我需要创建没有任何全局或静态变量的尾递归反向函数
我确实想出了这个函数,但它使用全局变量
list_t l;
list_t reverse(list_t list){
if(list.is_empty()==false){
l=list_make(list.get_first_elt(),l);
return reverse(list.get_rest_list());
}else{
return l;
}
}
请帮忙..
以下是编写函数时应遵循的规则● 这些过程中的每一个都必须是尾递归的。对于完全信用,例程必须提供正确的结果并提供尾递归的实现。● 在编写这些函数时,只能使用递归和选择。您不得使用 goto、for 、while或do-while。● 无静态或全局变量● 如果定义任何辅助函数,请务必将它们声明为"静态",以便它们在程序文件之外不可见。有关尾递归的更多信息,请参阅附录和帮助程序函数。
如果你只需要去掉全局变量,你可以传递一个引用参数:
static list_t reverse_helper(list_t list,list_t &l){
if(list.is_empty()==false){
l=list_make(list.get_first_elt(),l);
return reverse_helper(list.get_rest_list(),l);
}else{
return l;
}
}
list_t reverse(list_t list){
list_t l;
return reverse_helper(list,l);
}
相关文章:
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用正则表达式获取大括号块的列表
- 如何从远程 SFTP 服务器获取 HH-MM-SS 时间戳格式的文件列表
- 如何在 c++ stl 中获取列表中被推回的元素的地址,在常量时间内?
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 如何在两个列表中比较和获取非包含值
- 如何通过 UActor组件获取演员列表?
- 如何在Qt C++中获取所有可用主题的列表?
- 如何在 Windows 上获取带有 c++ 且没有 <dirent.h> 的特定扩展名的所有文件的列表
- 如何获取C++中的输入并将其"split"到列表中?换句话说,取 N 个输入并放入 N 长度的数组中
- 如何在类列表中获取参考?
- 如何在 c++ 中使用 ffmpeg 获取 DirectShow 设备列表?
- 是否可以使用 std::文件系统获取根名称列表?
- 如何仅在 2 个节点之间获取最短路径,给定邻接列表有向图?
- 使用初始化列表时如何获取私有数据?
- 获取可能的屏幕分辨率列表
- Cython正在获取C++对象列表的长度
- 将成员方法声明列表获取到文本编辑器中
- 当我使用运算符[]时,列表获取导致错误的项目