Reputation: 184
I'm trying to print the data in each Node in a Linked List using recursion, but I'm getting out of bounds errors, so I think something's wrong with my recursive function.
Here's the header file:
class List
{
public:
void print(std::ostream &out) const {}
private:
Node *head;
void printList(std::ostream&, const Node*) const;
}
Basically, I'm calling the private helper function from the public print
function. Here's the code for the two functions:
void List::print(std::ostream& out) const
{
printList(out, head);
}
void List::printList(std::ostream& out, const Node* n) const
{
if(n->next == NULL) {
out << n->data << std::endl;
return;
}
out << n->data << std::endl;
printList(out, n->next);
}
I think the problem lies within my if block because I need to stop if there is no next Node, but also print the data in the current Node before returning, but since I already call n->next
at the end in printList(out, n->next)
, do I need to do it in my if block?
Is there a better way to do this recursively? Does the code work for anyone else? I can't seem to get it to work.
Upvotes: 3
Views: 2101
Reputation: 9908
You need to change the condition inside if()
. You should check whether current node is NULL
or not instead of next node.
void List::printList(std::ostream& out, const Node* n) const {
if(n == NULL) {
return;
}
out << n->data << std::endl;
printList(out, n->next);
}
Upvotes: 5