'Circular linked list not working after appending 3rd node

It's Showing output for 2 nodes but after adding 3rd node it doesn't showing any output, what i'm doing anything wrong?? This is the append method that i have written all the other program have no errors i have tested all the things.

void append(nd element)
{
    nd temp = head;
    nd temp1 = null;
    while(temp != null)
    {
        temp1 = temp;
        temp = temp.nxt;
    }
    element.nxt = head;
    temp1.nxt = element;
}

void printCLL()
{
        nd temp = head;
        
        do
        {
            System.out.print(temp.data+" --> ");
            temp = temp.nxt;
        }
        while(temp != head);
}

public static void  main(String ar[])
{
        CLList clobj = new CLList();

        nd nn1 = new nd(10);
        clobj.head = nn1;    //working
        nd nn2 = new nd(20);   
        clobj.append(nn2);     //working
        nd nn3 = new nd(30); 
        clobj.append(nn3);   //not working
        nd nn4 = new nd(40);
        clobj.append(nn4);    //not working
         
        nd nn5 = new nd(25); 
        clobj.insertAfter(nn1, nn5); //this method also working if node added 
                
        System.out.println("Printing Circular LinkedList : ");
        
        clobj.printCLL();
    
}


Solution 1:[1]

Your loop condition temp1 != null is not correct, as it assumes the list is not cyclic and has an end. But as your list is cyclic, the loop will keep iterating.

So you should not compare with null but with head:

void append(nd element)
{
    if (head == null) {
        head = element;
    } else {
        nd temp = head;
        // Find node that precedes head
        while (temp.nxt != head) 
        {
            temp = temp.nxt;
        }
        temp.nxt = element;
    }
    element.nxt = head;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 trincot