title: C# size of a linked list (source code)
body: <p>I'm in my second year in computer science. Our teacher asked us to implement the class MyLinkedList (even tough it exists by default in C#) to improve our programming skills (Algorithms).</p>
  
  <p>I was able to implement a good part of the code and test it, but I was not able to implement the function that returns the size of the linked list.</p>
  
  <p>This is what I've done to far :</p>
  
  <pre class="lang-cs prettyprint-override"><code>class MyLinkedList
  {
  
      class Element
      {
          public float value;
          public Element next;
      }
  
  
      Element first;
  
      public MyLinkedList()
      {
          first = null;
      }
  
      public void add(float x)
      {
          Element e = new Element();
          e.value = x;
          e.next = first;
          first = e;
      }
  
      public float get(int i)
      {
          if (first == null)
          {
              throw new Exception("Empty list...no elements inside");
          }
          Element tmp = first;
          for (int j = 0; j &lt; i; ++j)
          {
              tmp = tmp.next;
              if (tmp == null)
              {
                  throw new Exception("...");
              }
          }
          return tmp.value;
      }
  
      public int size()
      {
          // I'm completely lost on that one, I have no clue on how
          // doing it.
      }
  
  }
  </code></pre>
  
  
  
  <pre><code>class MainClass
  {
      public static void Main(string[] args)
      {
          //To test the code
  
          MyLinkedList l = new MyLinkedList();
          l.add(3);
          l.add(5);
          l.add(8);
          Console.WriteLine(l.get(0));
          Console.WriteLine(l.get(1));
          Console.WriteLine(l.get(4));
      }
  }
  </code></pre>