Frage

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;
    }
}
War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top