문제

I have done a lot of development to my linked list program. When I want to reverse my list it says java heap space error(java.lang.OutOfMemoryError)

this is my reverse method:

    private void reverse()
    {
    Node start1=null;
    Node ptr1=start;
    while(ptr1!=null)
    {
        Node nnode=new Node();
        nnode.data=ptr1.data;

        if(isEmpty())
        {
            start1=nnode;
        }
        else
        {
            nnode.link=start1;
            start1=nnode;
        }
    }
    Node temp=start1;
    while(temp!=null)
    {
        System.out.println(temp.data);
        temp=temp.link;
    }
}
도움이 되었습니까?

해결책

The reason you run out of memory is this loop:

while(ptr1!=null)
{
    Node nnode=new Node();
    nnode.data=ptr1.data;

    if(isEmpty())
    {
        start1=nnode;
    }
    else
    {
        nnode.link=start1;
        start1=nnode;
    }
}

It keeps creating new Nodes until ptr1 becomes null, yet it never advances the ptr1.

You need to either change the loop condition to check start1, or change the body of the loop to move ptr1 to the next node.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top