title: Circular linked list in C++ (insert at beginning)
body: <p>I am studying old exams for an exam. One task is to implement an insert and print function that inserts elements at the beginning of a circular list. A program is provided to test the students solution. </p>
  
  <p>My solution for the insert is:</p>
  
  <pre><code>void Circular_List::insert(std::string const&amp; str)
  {
      if (entry == nullptr) {
          entry = new Element(str);
          entry -&gt; next = entry;
      }
      else {
          Element* temp = entry;
          entry = new Element(str);
          entry -&gt; next = temp;
      }
  }
  </code></pre>
  
  <p>My thought process: 
  <a href="https://i.stack.imgur.com/2O5W7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2O5W7.png" alt="enter image description here"></a></p>
  
  <p>It seems to work because my print: </p>
  
  <pre><code>void Circular_List::print() const
  {
      Element* temp = entry;
      while (temp -&gt; next != temp) {
          cout &lt;&lt; temp -&gt; name &lt;&lt; endl;
          temp = temp -&gt; next; 
      }
  }
  </code></pre>
  
  <p>prints the list in the right order EXCEPT for the element that I first added. I don't understand why it doesn't print the first element. 
  The program provided prints out 20 iterations. For example if I insert a,b,c,d,e the program will print </p>
  
  <blockquote>
    <p>d->c->b->a->a->a->a->a->a->a->a->a->a->a->a->a->a->a->a->a-></p>
  </blockquote>
  
  <p>This seems very off, should it not loop to the front of the list instead of just printing a? </p>
  
  <p>The test program:</p>
  
  <pre><code>  int j = 0;
    for (Circular_List::Iterator i = l.begin(); i != l.end() &amp;&amp; j &lt; 20; ++i, ++j)
    {
      cout &lt;&lt; *i &lt;&lt; "-&gt;";
    }
    cout &lt;&lt; endl;
  
  class Iterator
    {
    public:
      Iterator(Element* e) : pos(e) {}
      ~Iterator() = default;
      Iterator(Iterator const&amp;) = default;
      Iterator&amp; operator=(Iterator const&amp;) = default;
      bool operator!=(Iterator const&amp; i) { return pos != i.pos; }
      operator bool() { return pos != nullptr; }
      Iterator&amp; operator++() { pos = pos-&gt;next; return *this;}
      std::string operator*() { return pos-&gt;name; }
    private:
      Element* pos;
    };
  </code></pre>
  
  <p>I assume my insert is wrong but I can't figure out what I'm doing wrong?</p>