Help with recursion for search function.

I have a linkedList search function given and I am having a little trouble getting it to work. I've made a few attempts with no success. Any help would be appreciated.

Given normal search code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <class Type>
bool orderedLinkedList<Type>::search(const Type& searchItem) const
{
    bool found = false;
    nodeType<Type> *current; //pointer to traverse the list

    current = first;  //start the search at the first node

    while (current != NULL && !found)
        if (current->info >= searchItem)
            found = true;
        else
            current = current->link;
 
    if (found)
       found = (current->info == searchItem); //test for equality

    return found;
}//end search 


My attempt to make it a recursive search:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <class Type>
bool orderedLinkedList<Type>::search(const Type& searchItem) const
{
	//bool found = false;
	nodeType<Type> *current; //pointer to traverse the list
	current = first; //start the search at the first node
	if (first == NULL)
		return false;
	else if (current->info == searchItem)
		return true;
	else
	{
		current = current->link;
		return search(searchItem);
	}
}//end search 
When you calling search inside your function, you didn't pass it anything other that searcItem, so any changes to current will be lost (it will always starts witg current = first).
Possible solution: create another private search function, which takes searcItem and currentItem, and make your public search function call it. Like:
1
2
3
4
5
6
7
bool orderedLinkedList<Type>::search(const Type& searchItem) const
{
	
	nodeType<Type> *current;
	current = first;
        return private_search(searchItem, current);
}
- If anything, a recursive search function would just pass the address of the next node into the function and have a base case for if it reaches the end of the list and nothing has been found, and a base case for if the item was found.

- It seems pretty straightforward in my opinion.
Thank you for the advice MiiNiPaa, I am able to get it to work now.
Topic archived. No new replies allowed.