title: C++ How do I create a copy of a Linked List as a class object?
body: <p>I'm trying to make a copy of a linked List using the duplicate() method of the LinkedList class. I've been scratching my head all day about how to make this method work. </p>
  
  <p>The duplicate method needs to make an exact copy of the list, returning a pointer to the new list. I want to be able to call LinkedList methods on the new list. Should I be returning a LinkedList pointer? or a Node pointer? I feel like I'm totally missing something easy here. </p>
  
  <p>How would I even store the location of the new head node in the LinkedList pointer?</p>
  
  <pre><code>//LinkedList.h
  #pragma once
  
  #include&lt;string&gt;
  
  using namespace std;
  
  struct Node {
      string nodeData;
      Node* nextNode;
  };
  
  class LinkedList {
  public:
      LinkedList();
  
      ~LinkedList();
  
      bool insert(string givenData);
  
      bool remove(string givenData);
  
      void print() const;
  
      int count() const;
  
      int find(string givenData) const;
  
      bool removeAll();
  
      LinkedList* duplicate() const;
  
  private:
      Node* head;
  };
  
  
  //LinkedList.cpp duplicate() method
  LinkedList* LinkedList::duplicate() const {
      LinkedList* newList;
      Node* newHeadNode = new Node;
      Node* newNode = new Node;
  
      newHeadNode-&gt;nodeData = head-&gt;nodeData;
      newHeadNode-&gt;nextNode = head-&gt;nextNode;
  
      Node* currentNode = head-&gt;nextNode;
      Node* previousNode = head;
  
      while ((currentNode) &amp;&amp; (newNode-&gt;nodeData &gt; currentNode-&gt;nodeData)) {
          previousNode = currentNode;
          currentNode = currentNode-&gt;nextNode;
  
          newNode-&gt;nextNode = previousNode-&gt;nextNode;
          previousNode-&gt;nextNode = newNode;
      }
  }
  </code></pre>