Reputation: 129
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;
}
}
Upvotes: 2
Views: 197
Reputation: 726489
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 Node
s 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.
Upvotes: 2