Im having trouble turning this function into a recursion function, partly because I did it another way and now I cant think of how to do it recursively. Can you help?

int list::recursion(int item, int position)
{
	node* temp = startPtr; 
  
	while(temp != NULL)     
       {
        if(temp->item == item) 
          return position;  

        temp = temp->next;
		position++;
       }
      return 0;	
}

the function returns the position of an item in a linked list.

At first define position specifications. For example, what's a position for inexistent item value? What's a position of the 1st node - and so on...

you are starting temp at the beginning of the list each time through. I'd consider setting temp to the beginning of the list outside the function, then pass the item, the position and temp to the function. The terminating condition could be that the value of item is found in the list or the end of the list is found. If the end of the list is found then set position to zero. If the terminating conditions aren't found then advance temp to temp->next and send the new temp and both of the other variables to the recursive call.

int list::recursion(int item, int position, node * temp = startPtr)
{
        if (temp->next)
        {             
            if(temp->item != item)   
                 recursion(iItem, position + 1, temp->next);
        }
        else 
            position = -1; //not found flag
      return position;	
}

I'm not sure if this will compile, or even work properly (lol). I hate doing things recursively, it generally just runs slower and becomes much more complicated to implement. But this should give you a reasonable understanding of what you should do. When you call the function, don't use the last argument, since it defaults to the start of the linked list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.