多次拆分链表会导致堆栈溢出 c++
哦亲爱的;我似乎误会了这一点。
我想将单链表拆分 10,000 次,但显然(在你们帮助我之前我不知道这一点)它会导致堆栈溢出。
我对此真的很陌生,所以有什么办法我仍然可以做到这一点而不导致堆栈溢出?使用参考文献或其他什么?
方法如下:
Node* Node::Split()
{
if(next == NULL)
{
return this;
}
Node *newNode = this->next;
if(this->next != NULL)
{
this->next = newNode->next;
}
if(newNode->next != NULL)
{
newNode->next = newNode->next->Split();
}
return newNode;
}
Oh dear; I seem to have misthought this.
I would like to split a singly-linked list 10,000 times, but evidently (and I didn't know this before you guys helped me) it causes a stack overflow.
I'm really new to this, so is there any way I could still do this and not cause a stack overflow? Using references or something?
Here's the method:
Node* Node::Split()
{
if(next == NULL)
{
return this;
}
Node *newNode = this->next;
if(this->next != NULL)
{
this->next = newNode->next;
}
if(newNode->next != NULL)
{
newNode->next = newNode->next->Split();
}
return newNode;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将其编写为循环而不是递归调用。跟踪您在原始列表和新列表两端的位置,并将节点交替附加到每个列表。
You'll have to write this as a loop rather than a recursive call. Keep track of your position in the original list, and both ends of the new lists, and append nodes alternately to each list.
确保你的递归确实在某个时刻停止(尝试一个小数据集)。如果确实如此,那么您就没有问题,接下来要做的就是要求编译器为您增加堆栈大小。默认值相当小(我认为在 vc++ 10 上是 1 兆字节)。
Make sure your recursion does stop at some point (try a small data set). If it does then you have no problems there and the next thing to do is ask your compiler to increase the stack size for you. The default is quite small (I think it is one megabyte on vc++ 10).