If you have a circular linked list, then each node points to the next node in a continuous loop. So there is neither the last nor the first. In this situation, you only need one pointer to the data structure (which calls the "current" call), because you can go through the whole list until you return to where you started.
One node might look like this:
public class ListNode<T> { private T element; private ListNode<T> next; }
So, in this environment, when you add your first node to the list, it "next" pointer will point to itself. When you add a second node, each "next" pointer points to another. When you add the third node, each of them will point to the next, and apparently this is sorted out somehow. Each additional node added will be inserted at the appropriate place in the loop.
A good use for such a data structure is a graph that will be repeated every day or every hour. All events can be stored in a circular list, and the "current" pointer always indicates what is planned next time.
Obviously, when searching in such a list, you need to save the link to the first node. This is the only way to find out if you have looked at the entire list, since it does not end with a null "next" pointer.
Edit: As discussed in the (extensive) comment below, the tail pointer would seem to be very useful for insert operations. Here is the original method that I posted that was renamed insertAfter :
public void insertAfter(int data) { Link newLink = new Link(data); if (current == null) { newLink.next = newLink; current = newLink; } else { newLink.next = current.next; current.next = newLink; } }
A pointer to the tail would always point to the last node of the list. This will also be node until the first node, since the list is circular. Therefore, when managing pointers, be sure to support (tail.next == current) . Here is the new insertion method:
public void insert(int data) { Link newLink = new Link(data); if (current == null) { current = newLink; tail = newLink; newLink.next = newLink; // tail.next = current! } else { tail.next = newLink; // tail.next = current! newLink.next = current; current = newLink; // tail is unchanged, newLink is current } }
Inserting values ββshould correctly disable them. To maintain order while adding, use the add method:
public void add(int data) { this.insert(data); this.advance(); }
Here is the code for advance :
public void advance() { if (current != null) { tail = current; current = tail.next;
When used to create lists ...
list1.add(1); list1.add(2); list1.add(3); list2.insert(3); list2.insert(2); list2.insert(1);
... both lists are ordered 1-2-3 with 1 as current.