0

这是包含我的代码相关部分的代码大纲。

在 empprint 函数内部,我调用了一个 bfs 打印函数,它递归调用自身,直到打印完所有需要打印的内容,之后它应该将我返回给 empprint 函数。但是 bfsprint 中的 return 语句并没有让我回到 empprint。

我能想到的一个可能原因是 bfsprint 以递归方式调用自身,因此它只会返回调用它的最后一个 bfsprint 方法而不是 empprint 函数,但它似乎不能解决我的问题。我坚持执行不会终止的代码。

void node::empprint(node* myroot)
{
    //do something
    bfsprint(c);
    cout<<"pt 5"; //this cout is not reached
    return;
}

void node::bfsprint(Linklist<node*> noddy)
{
    // lot of code to implement breadth-first search. No issue

    if(c.getHead()==NULL) cout<<"1" //this does print 1 to output
    if(c.getHead()==NULL) return; //I think this should send me back to empprint
                                  // and print "pt 5" on output but program hangs.
                                  // instead of this happening
    bfsprint(c);
}

如果有人认为这可能会受到方法中其他代码的影响,我会添加它,但我认为不是这样。

4

1 回答 1

1

如果您的调用堆栈如下所示:

node::empprint
node::bfsprint
node::bfsprint

然后从最终调用返回将导致

node::empprint
node::bfsprint

所以你的 N 调用距离返回 node::empprint 很远。

您可以在课堂上设置一个布尔值以返回,但这有点hacky..

void node::bfsprint(Linklist<node*> noddy)
{
   if ( something ) { m_unwindstack = true; }

   // setting the bool to force returning early/stop recursion once m_unwindstack  is true to get back to empprint
   if ( m_unwindstack ) { return; }
}

编辑:顺便说一句,如果您使用 Linklist 做任何事情,自从您传递数据副本以来,您将永远不会看到更改。您应该传递一个参考 Linklist&。

Linklist 似乎也像您自己的课程?因此,如果您不使用引用,那么请确保它是可复制的,否则会发生不好的事情。

于 2013-09-14T10:34:44.403 回答