递归打印列表

Wit*_*g17 3 c++ recursion linked-list

我正在尝试使用递归打印链接列表中的每个节点中的数据,但是我遇到了越界错误,所以我认为我的递归函数有问题.

这是头文件:

class List
{
public:
    void print(std::ostream &out) const {}
private:
    Node *head;
    void printList(std::ostream&, const Node*) const;
}
Run Code Online (Sandbox Code Playgroud)

基本上,我从公共print函数调用私有帮助函数.这是两个函数的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

我认为问题在于我的if块,因为如果没有下一个Node我需要停止,但是在返回之前还要在当前Node中打印数据,但是因为我已经n->next在最后调用了printList(out, n->next),我是否需要在我的if块?

是否有更好的方法递归地执行此操作?代码是否适用于其他任何人?我似乎无法让它发挥作用.

Shr*_*n40 5

你需要改变里面的状况if().您应该检查当前节点是否是NULL下一个节点.

void List::printList(std::ostream& out, const Node* n) const { 
    if(n == NULL) { 
        return; 
    } 
    out << n->data << std::endl; 
    printList(out, n->next); 
}
Run Code Online (Sandbox Code Playgroud)