运行 时递归函数崩溃
Recursive function is crashing when run
我正在编写一个涉及链表的程序。我写了一个函数 returns 链表中的第 n 个节点,它递归地调用自己。我的程序编译并运行直到递归函数然后崩溃。这是节点的构造函数以及递归函数:
LinkedList::LinkedList():
head(head){
sizeInt = 0;
}
Node* LinkedList::get_nth(const int& n) const {
Node* node = new Node();
for(int counter = 1; counter <= n; counter++){
node = get_nth(counter + 1);
}
return node;
}
这个函数有什么问题?如果您需要更多详细信息或代码,请告诉我。
没有什么可以阻止递归(除其他外,有一个递归调用 n
增加到 n + 1
。)
这会使您的堆栈溢出,程序将因此崩溃。
递归是无限的。在每次调用 get_nth
时,您都会启动一个循环,该循环最初调用 get_nth(1)
然后将调用 get_nth(1)
然后将调用 get_nth(1)
... 直到堆栈 space用完了。
解决方案提示:递归线性搜索不需要循环。
我正在编写一个涉及链表的程序。我写了一个函数 returns 链表中的第 n 个节点,它递归地调用自己。我的程序编译并运行直到递归函数然后崩溃。这是节点的构造函数以及递归函数:
LinkedList::LinkedList():
head(head){
sizeInt = 0;
}
Node* LinkedList::get_nth(const int& n) const {
Node* node = new Node();
for(int counter = 1; counter <= n; counter++){
node = get_nth(counter + 1);
}
return node;
}
这个函数有什么问题?如果您需要更多详细信息或代码,请告诉我。
没有什么可以阻止递归(除其他外,有一个递归调用 n
增加到 n + 1
。)
这会使您的堆栈溢出,程序将因此崩溃。
递归是无限的。在每次调用 get_nth
时,您都会启动一个循环,该循环最初调用 get_nth(1)
然后将调用 get_nth(1)
然后将调用 get_nth(1)
... 直到堆栈 space用完了。
解决方案提示:递归线性搜索不需要循环。