簡體   English   中英

使用列表庫進行遞歸列表搜索

[英]List-Search with recursion by using list library

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值。 但是一旦返回,它總是返回一個垃圾值。 我以為返回后仍然有步驟要走,但我看不到哪里和如何做。

存在一個不返回值的代碼路徑。 listRecSearch(list, data); 應該成為return listRecSearch(list, data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM