title: Why does my while loop produce an extra value in Java?
body: <p>I am trying to create a while loop in Java that counts the number of nodes in a doubly linked list. However my while Loop is producing an extra value and I can not seem to figure out why. Could someone please help me?</p>
  <p>The method below is used to count the number of nodes in a list I defined in the Main Method. I called the getListSize() method, in the main method.</p>
  <pre><code> public static &lt;E&gt; int Size(Linked&lt;E&gt; L) { 
  
        int counter=0;
        while (L.header != null &amp;&amp; L.header != L.trailer)
        {
          L.header= L.header.getNext();
          counter++;
          
        }
        return counter;
    }
  
  
  public static void main(String[] args)
    {
       Linked&lt;String&gt; list = new Linked&lt;String&gt;();
       list.addFirst(&quot;1&quot;);  
       list.addFirst(&quot;4&quot;);
        list.addLast(&quot;3&quot;);
        list.addLast(&quot;2&quot;);
        
              
        System.out.println(Size(list));
        
    }
  </code></pre>
  <p>But I get an output of 5 instead of 4</p>
  <p>Node and Linked Classes</p>
  <hr />
  <p>public class Linked {</p>
  <pre><code>  public static class Node&lt;E&gt; {
  
      private E element;               
      private Node&lt;E&gt; prev;           
      private Node&lt;E&gt; next;            
  
      
      public Node(E e, Node&lt;E&gt; p, Node&lt;E&gt; n) {
        element = e;
        prev = p;
        next = n;
      }
  
      public E getElement() { return element; }
  
      public Node&lt;E&gt; getPrev() { return prev; }
  
      public Node&lt;E&gt; getNext() { return next; }
  
      public void setPrev(Node&lt;E&gt; p) { prev = p; }
      public void setNext(Node&lt;E&gt; n) { next = n; }
      
    } 
  
  
    
    public Node&lt;E&gt; header;                    
    public Node&lt;E&gt; trailer;                   
    private int size = 0;                      
  
    
    public Linked() {
      header = new Node&lt;&gt;(null, null, null);      
      trailer = new Node&lt;&gt;(null, header, null);   
      header.setNext(trailer);                    
    }
  </code></pre>
  <p>}</p>