2

I have this function:

    void TraverseRecursive ( Node * head, void (*visit) (Node *) )
    {
      if ( head != nullptr )
      {
        visit( head ) ;
        TraverseRecursive( head->next, visit ) ;
      }
    }

And I'm trying to call it in main.cpp with

TraverseRecursive ( head, TraverseRecursive ) ;

Which gives me the error "argument of type "void (*)(Node *head, void (*visit)(Node ))" is incompatible with parameter of type "void ()(Node *)" "

So how do I correctly call it? I am just learning linked lists and obviously don't understand what

 void (*visit) (Node *)

means at all.

1
  • 1
    If you're just learning about recursion then by all means recurse away, but as @ikegami points out, traversing a list is an inherently non-recursive activity. You pay a run-time price for using recursion, so avoid it when possible unless it truly simplifies your code. Commented May 31, 2014 at 23:26

2 Answers 2

1

The second argument should be a function to call back for every node in the list. It only takes a single parameter (the node to "visit").

void visitor(Node *node)
{
  printf("%s\n", node->data);  // Or whatever
}

TraverseRecursive( head, visitor ) ;

Side note: What wasteful use of recursion. If you're lucky, the compiler will optimize it away. You should be using

void TraverseRecursive( Node * head, void (*visit) (Node *) )
{
  for (; head != nullptr; head = head->next)
  {
    visit( head ) ;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks people! I got excited to use recursion because I was going to call a display function, then just switch the visit... and Traverse... lines to make it display backwards. I was trying to combine them into one horrible abomination, but thanks to ya'll now I can call Display from my traverse!
0
void (*visit) (Node *)

means "pointer to a function taking one argument of type Node* and returning void". But TraverseRecurive takes two argumenst and is therefore of different type. You need to define a function like

void doSomething(Node* n)
{
}

and pass it to TraverseRecursive

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.