I am trying to make a recursion function that will print all the elements in a linked list backward.
This is the function that I have made:
void lista::printBack(node *pocetak) {
if (pocetak==NULL) {
return ;
}
printBack(pocetak->sljedeci);
cout<<pocetak->podatak<<" ";
}
Now for the question. I want to set default value of the parameter pocetak, so that the function can print the list without the start value.
But when I do this:
void lista::printBack(node *pocetak = head)
{
if (pocetak==NULL) {
return ;
}
printBack(pocetak->sljedeci);
cout<<pocetak->podatak<<" ";
}
I always get a error message:
main.cpp:17:19: error: no matching function for call to ‘lista::printBack()’
main.cpp:17:19: note: candidate is:
lista.h:20:10: note: void lista::printBack(node*)
lista.h:20:10: note: candidate expects 1 argument, 0 provided
Is that any way I can do this? Thank you.
You need to specify the default argument in the header file (the implementation
lista::printBack(node* pocetak=head)is not enough)Note that this means you will need to have a valid
node* headdeclared before thelistatype is defined, the best way for which is t use forward declaration (see above). Also,headwill be a global variable, which is usually not a good idea.EDIT: fixed type names