title: Add element at the end of a Linked List in java
body: <p>We started learning Lists in school but I don't really understand how they work. As homework we have to write a method add that adds an element at the end of the list. I don't know why, but when I add more nodes, the Lists only saves the first two. I want to know why and what should I change. This is the code (I am not allowed to change anything from the given code. I can only create new methods...) </p>
  
  <pre><code>public class HeadList {
  
      Entry head;
  
      public HeadList() {
          head = null;
      }
  
      /**
       * Appends a new element with value info to the end of this list
       * @param info value of the new element
       */
      public void add(int info) {
          //TODO
  
         Entry node = head;
  
          if (head != null) {
              if (node.next == null){
                  node.next = new Entry(node, null, info);
              }
              else{
                  Entry n = node.next;
                  while(n != null){
                      n = n.next;
                  }
                  node = new Entry(node, null, info);
              }
          }
          else
              head = new Entry(null, null, info);
  
      }
      @Override
      public String toString() {
          String out = "[";
          if (head != null) {
              out += head.elem;
              Entry tmp = head.next;
              while (tmp != null) {
                  out = out + "," + tmp.elem;
                  tmp = tmp.next;
              }
          }
          out += "]";
          return out;
      }
  
      public static void main(String[] args) {
          HeadList l = new HeadList();
          l.add(6);
          l.add(7);
          l.add(8);
          l.add(9);
          System.out.println("empty list: " + l);
          // Test implementation
  
      }
  
      class Entry {
  
          Entry first;
          Entry next;
          int elem;
  
          public Entry(Entry first, Entry next, int elem) {
              this.first = first;
              this.next = next;
              this.elem = elem;
          }
  
      }
  
  }
  </code></pre>