title: Circular linked list in Java, when to point to first node?
body: <p>I need to implement a circular single-linked list data structure. What I'm having trouble understanding is when and where do I have to state that the final node of the list must point to the first node. I have the following empty constructor to build the list:</p>
  
  <pre><code>public class SList&lt;E&gt; implements IList&lt;E&gt; {
  
      protected SNode&lt;E&gt; firstNode = null;
  
      public SList() {
          firstNode = null;
      }
  </code></pre>
  
  <p>So basically each list starts with a null object that points to null again, signifying the end of the list:</p>
  
  <pre><code>public class SNode&lt;E&gt; {
  
  E elem;
  public SNode&lt;E&gt; nextNode = null;
  ...
  </code></pre>
  
  <p>What I am unaware of however is how to make it so that when the list contains at least one node, that node will point to the first node of the list. </p>
  
  <p>For example, taking a look at this addLast() method that I implemented for my regular linked list:</p>
  
  <pre><code>    public void addLast(E newElem) {
          SNode&lt;E&gt; newNode= new SNode&lt;E&gt;(newElem);
          SNode&lt;E&gt; nodeTraveler = firstNode;
          while (nodeTraveler.nextNode != null) {
              nodeTraveler= nodeTraveler.nextNode;
          }
          nodeTraveler.nextNode = newNode;
       }
  </code></pre>
  
  <p>I would have to change it into something like:</p>
  
  <pre><code>    public void addLast(E newElem) {
      SNode&lt;E&gt; nodeTraveler = firstNode;
      SNode&lt;E&gt; newNode = new SNode&lt;E&gt;(newElem);
      while (nodeTraveler.nextNode != firstNode){
          nodeTraveler = nodeTraveler.nextNode;
      }
      nodeTraveler.nextNode = newNode;
      newNode.nextNode = firstNode;
  }
  </code></pre>
  
  <p>nodeTraveler would stop traversing the list once it's next node matched that of the firstNode (meaning it's at the last position), and then it would change its nextNode to the one we want to add, newNode, and point newNode to the firstNode. </p>
  
  <p>Theoretically, that should work, but since I'm never actually pointing the last element to the first one prior to this method (which is my main question, how to point the last element to the first one by default), I get a nullPointer exception when the code reaches the while iteration.</p>
  
  <p>Any help would be appreciated, thanks.</p>