int listRecSearch(list<int>list, const int data)
{
if (list.empty())
{
cout << "The number is not in the list, try again..." << endl;
return -1;
}
else if (list.back() == data)
{
// cout << "list.size(): " << list.size() << endl;
list.pop_back();//I needed the index begins from 0 instead of 1
return list.size();
}
else
{
// cout << "list.back(): " << list.back() << endl;
list.pop_back();
listRecSearch(list, data);
}
}
//funtion used
int main()
{
list<int>list = listGenerator(size);//generate a list with 20 random numbers.
cout << "Specify the element to be searched for: ";
cin >> data;
int position = listRecSearch(list, data);
if (position > -1)
cout << "\nFind the element at position: " << position << endl;
}
函数listRecSearch
能够显示正确的list.size()
值并更正pop_back值。但是一旦它返回,它总是返回一个垃圾值。我想在返回后仍然有一些步骤,但我不知道在哪里以及如何。
答案 0 :(得分:2)
存在不返回值的代码路径。 listRecSearch(list, data);
应该成为return listRecSearch(list, data);
。