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}' –