title: Inserting element into linked list while traversing C++
body: <p>I'm new to C++ and having some difficultly with the use of shared ptrs. I've been able to construct a linked list. I want to traverse the linked list, and when the nodes (elements) have a valid to_add field, to add the element into the list, and continue.</p>
  <pre><code>
  class Element{
  public:
      char el = 'Z';
      std::shared_ptr&lt;Element&gt; next;
      char to_add = 'Z';
      Element(char input){
          el = input;
          next = nullptr;
      }
  };
  </code></pre>
  <p>^ structure of node. I'm looking at the to_add field to see if there's an element to add in.</p>
  <pre><code>class Polymer{
  public:
      std::vector&lt;Instruction&gt; instruction;
      std::shared_ptr&lt;Element&gt; extract_and_store_input(std::ifstream &amp;file);
      void prepare_insertion(std::shared_ptr&lt;Element&gt; head);
      void insert_elements(std::shared_ptr&lt;Element&gt; head);
      Polymer(std::ifstream &amp;file){
          std::shared_ptr&lt;Element&gt; head = extract_and_store_input(file);
          prepare_insertion(head);
          insert_elements(head);
  
      }
  };
  
  </code></pre>
  <p>^ calling code format</p>
  <p>v problem is somewhere here</p>
  <pre><code>std::shared_ptr&lt;Element&gt; add_element(std::shared_ptr&lt;Element&gt; head_cpy){
      auto tmp = head_cpy-&gt;next;
      head_cpy-&gt;next = std::make_shared&lt;Element&gt;(head_cpy-&gt;to_add);
      head_cpy-&gt;next = tmp;
      return tmp;
  }
  
  
  void Polymer::insert_elements(std::shared_ptr&lt;Element&gt; head) {
  
      auto trav = head;
      auto tmp= head;
  
      // for (int i = 0; i &lt; num_steps; i ++)
      while (trav-&gt;next != nullptr) {
          std::cout&lt;&lt;trav-&gt;el&lt;&lt;std::endl;
          if (trav-&gt;to_add != 'Z'){
              std::cout&lt;&lt;&quot;adding&quot;&lt;&lt;trav-&gt;to_add&lt;&lt;std::endl;
              trav=add_element(trav);
              trav=trav-&gt;next; // progress forward twice
          }
          trav=trav-&gt;next;
      }
  
  //    while (tmp-&gt;el != 'Z'){
  //        std::cout&lt;&lt;tmp-&gt;el&lt;&lt;std::endl;
  //        tmp=tmp-&gt;next;
  //    }
  
  
  }
  </code></pre>
  <p>I think that the issue may be that the pointer doing the traversal (trav) is updating the list itself, rather than progressing through the list? I would really appreciate any insights!</p>
  <p>If anyone recognises the q, it's from AoC day 14 :) I'm sure there are better ways to do it, but I'd like to understand the problem here first!</p>