MrPickles7
MrPickles7

Reputation: 692

How to call a recursive linked list traversal function in C++

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.

Upvotes: 2

Views: 1160

Answers (2)

ikegami
ikegami

Reputation: 385647

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 ) ;
  }
}

Upvotes: 1

wonce
wonce

Reputation: 1921

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

Upvotes: 0

Related Questions