0
我正在为我的大学做作业。我需要创建递归函数。使用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);
请注意SUM函数必须是尾递归,我不能用静态或全局变量。
到现在为止我已经跟这个是给了我错误的答案:
int sum(list_t list) {
if(list.get_rest_list().is_empty())
return list.get_first_elt() + sum(list.get_rest_list());
}
非常感谢你哟让我很快乐.. –
可你还告诉我,为什么这个函数总是返回true .'bool list_contains(list_t名单,诠释ELT){ \t如果(名单.is_empty()) return false; \t \t 如果\t(list.get_first_elt()== ELT){ \t \t \t返回真; \t \t} else { \t \t \t list_contains(list.get_rest_list(),elt); \t \t} \t \t}' –