title: How to calculate the length of the linked list using constant time (O(1))
body: <p>I have a function to calculate the length of the list. But this is in linear time. How could I convert this to constant time (O(1))</p>
  
  <pre><code>struct Node
  {
      T data;
      Node *next;
  };
  </code></pre>
  
  <p>with <code>Node *front;
      Node *back;</code></p>
  
  <p>This is function to calculate the length of the linked list</p>
  
  <pre><code>int length() const
  {
      Node *p = front;
      int n = 0;
  
      while (p != nullptr)
      {
          n++;
          p = p-&gt;next;
      }
  
      return n;
  }
  </code></pre>