开发者

Splitting linked list so many times puts into stack overflow c++

Oh dear; I seem to have misthought this.

I would li开发者_StackOverflow社区ke 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;
}


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜