You already have object x. This probably the current last element of the linked list. Now, you create a new object T and link it as the element after X
X // Lets assume X.next == NULL. So linked list looks like this X -> Null
X.next = T // Now X.next == T and T.Next == NULL, So linked list looks like this X -> T -> Null.
T.next = X.next // Now T.next == T. So linked list is X -> T <->T
This way, when you reach the end of the linked list, it will always return the last element instead of returning NULL.
If you are writing a simple algorithm for this, first you have to create an element and then point its next variable to it self.<First_element>.next = <First_element>. So the logic will work for all the instances.
Here is a simple experiment.
class Node{
Node next = null;
int id =-1;
}
public class LinkedList{
public static void main (String args[]){
Node x = new Node();
x.id = 0;
x.next = x;
// Now add a new element
Node t = new Node();
t.id =1;
x.next = t;
t.next = x.next; // Now we have a linked list of 2 elements
Node mynode = x;//First element of linked list
for(int i =0; i < 3; i++){
System.out.println(mynode.id);
mynode = mynode.next;
}
}
}
Output:
0
1
1
t.next = x.netshould be done first.tafterx.