template<class Type>
int StringList<Type>::find(Type value)
{
int count = 0;
// Start of linked list
Node<Type> *current = head;
// Traverse list until end (NULL)
while (current != NULL)
{
// Increase counter if found
if (current->data == value)
{
count++;
}
// If not, move to the next node
current = current->next;
}
cout << value << " was found " << count << " times" << endl;
return 0;
// same function but using Recursive method
// Start of linked list
Node<Type> *current = head;
int count = 0;
// Thinking this is the base case, since its similar to the while loop
if (current == NULL)
{
return 0;
}
// same as the while loop, finding the value increase the count, or in this case just prints to console
if ((current->data == value))
{
cout << "Found match" << endl;
return 0;
}
else
{ // If it didnt find a match, move the list forward and call the function again
current = current->next;
return find(value);
}
}
函數應該找到搜索到的值並返回鏈接列表中某個值的次數。在鏈表中查找值的遞歸方法
如何將第一個使用while循環的方法轉換爲執行相同的事情但使用遞歸的東西?
你有什麼嘗試嗎? –
是的,向下滾動 – CodeSpyder
看起來你是那裏的大部分,但我不認爲你想在比賽中立即返回。相反,繼續直到空,並且每次迭代都返回到目前爲止發現的數字。 – user4581301