我正在练习 LLL 递归,目前我陷入了这个问题。这是我到目前为止所拥有的:
count_last(node* head, int &last_node_data)
{
if(!head) return 0;
if(!head->next)
{last = head->data;
return 0;
}
count_last(head->next,last);
if(head->data == last)
//Increase count by 1;
}
如何增加计数?当我用递归向后工作时(从列表的末尾开始),我真的很挣扎。谢谢!
你可以:
尝试这样的事情:
int count_last(node* head, int &last_node_data)
{
if (!head) return 0;
// if you don't want to include the last
// node in the count, you can filter it out...
//
// if (!head->next) return 0;
return ((head->data == last_node_data) ? 1 : 0) + count_last(head->next, last_node_data);
}
int count_last(node* head, int& last_node_data)
{
if(!head) return 0;
if(!head->next) {
last_node_data = head->data;
return 0;
}
int count += count_last(head->next, last_node_data);
if(head->data == last_node_data)
++count;
}