title: Singly Linked Lists: How to add the head
body: <p>I have an assignment to implement a singly linked list. I am trying to figure out how to get the head but I end up getting stack overflow errors or null pointer errors. Could someone help me. I have displayed the relevant pieces of code:</p>
  
  <pre><code>public class Llist {
  
      private Object data;
      private Llist next;
      private Llist head = new Llist(null, null);
  
      public Llist(Object d) {
          this(d, null);
      }
  
      public Llist(Object d, Llist n) {
          data = d;
          next = n;
      }
  </code></pre>
  
  <p>I have a method to add a node, it will check whether or not there is a head, if there isnt then the new node is the head:</p>
  
  <pre><code>public static Llist add(Llist l, Object d) {
      Llist n = new Llist(d,l);
      if(l.head == null) {
          l.head = n;
      }
      return n;
  }
  </code></pre>
  
  <p>Currently I get a stack overflow error... but if I remove the line of setting the head to null in the 2</p>