title: Copy Linked List to Another List?
body: <p>I need help in linked list, to make a function for copy a list to another list</p>
  
  <p>I code with Visual Studio 2012. Here is my code and the error that I get:</p>
  
  <p>ERROR: </p>
  
  <blockquote>
    <p>Unhandled exception at 0x0111544F in linked list.exe: 0xC0000005:
    Access violation writing location 0xCDCDCDCD.</p>
  </blockquote>
  
  <p>Could someone please tell me what's the mistake and how to fix it?</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  struct node
  {
      int info;
      node *next;
  };
  
  void PrintList (node *C)
  {  
      node *P;
      cout&lt;&lt;"Node content = (";
      P = C;
      while(P!=NULL)
      {
          cout&lt;&lt;P-&gt;info;
          P = P-&gt;next;
          if(P != NULL) 
              cout&lt;&lt;",";       
      }
      cout&lt;&lt;")"&lt;&lt;endl;
  }
  
  void copylist (node *Y, node **Z)
  {
      node *P, *Q;
      int temp;
      if (Y==NULL)
      {
          cout&lt;&lt;"the list is empty"&lt;&lt;endl;
          *Z=NULL;
      }
      else
      {
          P=Y;
          Q=*Z;
          while (P-&gt;next!=NULL)
          {
              temp=P-&gt;info;
              Q-&gt;info=temp;
              P=P-&gt;next;
              Q=Q-&gt;next;
          }
      }
  }
  
  void insertnode (int *A, node **Q)
  {
      node *N, *P;
  
      N=new node;
      N-&gt;info=*A;
      N-&gt;next=NULL;
  
      if(*Q==NULL)
          *Q=N;
      else
      {
          P=*Q;
  
          while (P-&gt;next!=NULL)
              P=P-&gt;next;
  
          P-&gt;next=N;
      }
  }
  
  int main ()
  {
      node *z;
      node *duplicate;
      z=NULL;
      duplicate=new node;
      int e;
      int i;
      int *temp;
      temp=new int;
  
      cout&lt;&lt;"the number of element : ";
      cin&gt;&gt;e;
  
      cout&lt;&lt;" LIST Z CONTENT : " &lt;&lt;endl;
      PrintList (z);
  
      for (i=0;i&lt;e;i++)
      {
          cin&gt;&gt;*temp;
          insertnode(temp, &amp;z);
      }
  
      copylist(z,&amp;duplicate);
  
      cout&lt;&lt;" DUPLICATE LIST CONTENT : "&lt;&lt;endl;
      PrintList(duplicate);
  }
  </code></pre>