title: Retrieving an element by index in Java linked list
body: <p>I am writing a linked list (not using Java's) and trying to create a get method to return an element of the list by its index number. Originally, I wrote this using a for loop. My code is repeatedly failing a test in which it retrieves the element at index 0 (I seem to be able to retrieve elements at other indices). curr is just for me to keep track of the current node.</p>
  
  <pre><code>public double get(int index) {
      Node curr = this.sentinel.next;
  
      for (int i = 0; i &lt; this.size(); i++) {
          if (i == index) {
              return curr.data;
          }
          curr = curr.next;
          if (index &gt; numElts) {
              return Double.NaN;
          }
          if (index &lt; 0) {
              return Double.NaN;
          }
      }
      return Double.NaN;
  }
  </code></pre>
  
  <p>I thought the for loop might be what was giving me trouble, so I wrote it as a while loop.</p>
  
  <pre><code> while (curr != null) {
    if (i == index) {
     i++;
     return curr.data;
   }
   curr = curr.next;
   }
  </code></pre>
  
  <p>However, I'm still having trouble retrieving the element at the 0 index. I appreciate any input on how these methods of traversal might be problematic. I'm kind of lost. Also apologies if my formatting is off, still getting used to formatting on this site.</p>