title: Unexpected Behaviour of LinkedList in Java
body: <p>I am attempting to solve a problem on Hacker Rank that requires the use of <code>LinkedList</code>, and I found something strange. The goal is to print the <code>LinkedList</code> in reverse.</p>
  
  <p>I have tried debugging the program, but I'm unable to find anything wrong.</p>
  
  <p>In the first piece of code below, I'm only able to put the first and last elements of the <code>LinkedList</code> into an <code>ArrayList</code>.</p>
  
  <pre><code>static void reversePrint(SinglyLinkedListNode head) {
      List&lt;Integer&gt; tempList = null;
  
      if (head == null)
          return;
      else {
          tempList = new ArrayList&lt;&gt;();
          tempList.add(head.data);
          while(head.next != null)
              head = head.next;
          tempList.add(head.data);
      }
      System.out.println("Size of the List -"+tempList.size());
      for(int i = tempList.size()-1; i &gt;= 0; i--)
          System.out.println("Index +"+i+" "+tempList.get(i));
  }
  </code></pre>
  
  <p>In the following piece of code, I am getting <code>java.lang.OutOfMemoryError: Java heap space</code> and I am unable to understand what is actually causing this error.</p>
  
  <pre><code>static void reversePrint(SinglyLinkedListNode head) {
      List&lt;Integer&gt; tempList = null;
  
      if (head == null)
          return;
      else {
          tempList = new ArrayList&lt;&gt;();
          while(head.next != null)
              tempList.add(head.data);
          head = head.next;
      }
      tempList.add(head.data);
      System.out.println("Size of the List -"+tempList.size());
      for(int i = tempList.size()-1; i &gt;= 0; i--)
          System.out.println("Index +"+i+" "+tempList.get(i));
  }
  </code></pre>