在 C++ 中获取反向列表

get reverse list in c++

本文关键字:列表 获取 C++      更新时间:2023-10-16

我正在为我的大学做作业。我需要创建递归函数。

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