int findLargest (ListNode *p)
// --------------------------------------------------------------------------
// Preconditions: list head pointer is passed as a parameter.
// Postconditions: returns the largest value in the linked list.
// --------------------------------------------------------------------------
{
if (p->item != NULL)
{
int largest = p->item;
if (largest > p->next->item)
...
}
...
}
Is it possible to write this recursive function passing only a pointer as a parameter? I can’t figure out how to do this without adding more parameters. Any ideas? I am only using sequential search. Nothing fancy.
Here is the portion of class List that will be needed:
struct ListNode
{
ListItemType item; // A data item on the list.
ListNode *next; // Pointer to next node
}; // end ListNode
ListNode *head; // Pointer to linked list of items.
I am mainly worried about the feasibility of the problem. Can this be done with only a pointer as a parameter?
This is definitely feasible, although I agree that recursion is not the best solution to solve this problem. In this case, non-recursive code would be easier to read (recursion), faster (overhead of function call), and more memory efficient (obviously more stack frames).
Each recursive call returns the greater of either it’s value or the value from the rest of the list.
Recursion stops when the
nextitem is null.