This is my Java program to insert an element in a linked list. I have written the following code:
import com.expanion.code.evalution.*;
public class Answer implements QuestionInterface {
@Override
public SchNode func(SchNode head, int index, char ch )
{
SchNode ptr;
SchNode temp = new SchNode(ch);
int count=1;
for(ptr = head ; ptr!=null ; ptr=ptr.nextNode)
{
count++;
if(index==count )
{
if(ptr.nextNode == null)
{
ptr.nextNode = temp;
temp.nextNode = null;
ptr=temp;
}
else
{
ptr.nextNode = temp;
temp.nextNode = ptr.nextNode;
ptr=temp;
}
}
}
return ptr;
}
}
While compiling it, the compiler shows that the loop has crashed. Since I am a beginner in Java, I haven't been able to find it.
I see that this causes a cycle
as temp.nextNode points to itself.
U need to interchange these lines