Linked list without using collections in Java

2.3k Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

I see that this causes a cycle

 ptr.nextNode = temp;
 temp.nextNode = ptr.nextNode;

as temp.nextNode points to itself.

U need to interchange these lines