title: Creating a deep copy of a doubly-linked list node
body: <p>I have my node defined something like:</p>
  
  <pre><code>class LLNode
  {
  public:
      std::shared_ptr&lt;LLNode&gt; prev;
      std::shared_ptr&lt;LLNode&gt; next;
      std::shared_ptr&lt;int&gt; data;
      LLNode(void)
      : prev(std::shared_ptr&lt;LLNode&gt;(nullptr)),
      next(std::shared_ptr&lt;LLNode&gt;(nullptr)),
      data(std::shared_ptr&lt;int&gt;(nullptr))
      {
      }
  
      LLNode(const LLNode &amp;node)
      : prev(std::shared_ptr&lt;LLNode&gt;(node.prev == nullptr?nullptr:new LLNode(node.prev))),
      next(std::shared_ptr&lt;LLNode&gt;(node.next == nullptr?nullptr:new LLNode(node.next))),
      data(std::shared_ptr&lt;int&gt;(new int(node.data)))
      {
      }
  };
  </code></pre>
  
  <p>However, if I have a node which is linked to another node (which obviously will often be the case), copying node A will instantiate a copy of the next node B, which in turn will try to instantiate a copy of node A, which will try to copy node B, etc. etc. until there's a stackoverflow or memory error. This could be fixed by only instantiating a new copy of next (or prev), but then nothing linked previously (or next) to this node will be copied.</p>
  
  <p>Is there a good way to copy a doubly linked list node?</p>