1
votes

I tried implementing the insert method for circular linked list. I think I had some success.

Problem: When I display the list. The display method will loop because every next variable of the link is linked to a non-null node object. So head will never be a null object. From what I recall about singly linked list, head always point to the first node in the list or the first node with data inside of it.

My conceptual understanding of circular linked list: From what I can understand circular linked is somewhat like a singly linked list but with a slight twist: the next variable of the tail object points to the head.

I'm coding it like the diagram has presented provided by the source link.

Source: http://sourcecodemania.com/circular-linked-lists/

public void insert(String data)
    {
        Link link = new Link(data);

        if(head == null)
        {
            head = link;
            tail= link;
        }
        else
        {
            tail.next = link;
            tail = link;
            tail.next = head;

        }
    }


public void display()
    {


        // good implementation for display #2
        while(head != null)
        {
        //  System.out.println (head.data);
            head = head.next;
        }
    }
2

2 Answers

1
votes

Once you insert at least one element, you would never come across null. It will keep on going till infinity.

Also, it might not be a good idea to modify head just for displaying the list. Operation like display should not have any side effects.

In stead, keep a member field size in your list class and update it in each insert and delete method.

Now you would know how many times you should iterate the loop.

ListClassName current = head;    // Head is not modified.
for (int i = 0; i < this.size; i++) {
//   System.out.println (current.data);
     current = current.next;
}

Good luck.

1
votes

You can keep a reference to the first Link object and check to make sure head is not equal to this object while looping:

 public void display()
{
    boolean first=true;
    Link firstItem=null;
    // good implementation for display #2
    while(head != null && head!= firstItem)
    {
       if(first){
           firstItem=head;
           first=false;
        }
    //  System.out.println (head.data);
        head = head.next;
    }
}