Search code examples
javacircular-list

Singly Linked Circular List Add method


I am creating a singly linked circular list and I don't seem to understand why it is not working. Here is my code. Would someone help me and point out what am I doing wrong? I am able to add the first node but I don't understand how to add the second node. Could someone show me how to change it. I think my list is traversing endlessly that's why.

public class CircularList <E> {
       private Node<E> head;

       private class Node <E>
       {
          E data;
          Node <E> next;

          public Node(E data, Node<E> next)
          {
             this.data = data;
             this.next = next;
          }
          public Node(E data)
          {
             this.data = data;
             this.next = null;          
          }
       }//node
       public CircularList()
       {
          head = null;

       }

       public void add(E data)
       {
           Node <E> temp = new Node <E> (data);
           if(head==null)
           {
               head=temp;
               temp.next=temp;
               System.out.println(head.next.data);
            }
           else
           {
               Node<E> temp2 = head.next;
               while(temp2!=head)
               {
                   if(temp2.next==head)
                   {
                       temp2.next=temp;
                       temp.next=head;
                   }
                   temp2=temp2.next;
               }

           }
       }

Solution

  • Update your else part with this;

               Node<E> temp2 = head;
               while(temp2.next != head)
               {
                   temp2=temp2.next;
               }
               temp2.next=temp;
               temp.next=head;