阅读背景:

在链表中查找值的递归方法

来源:互联网 
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);
}

}
template<class Type>
int StringList<Type>::find



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: