0

I have created linkedlist class, it works fine. But i'm having problems with copy constructor. It creates a copy which contains the same elements when i print. But later when i remove an element (by calling the deleteHead() function given below )from the original list, created copy is also changed and then it contains some garbage value. What i'n understanding is that, i'm not able to create a deep copy,which i wanted. How can i copy a list, such that when i remove all the elements from the original list, copy still contains all the elements? Here's the code with relevant functions.

class Node{
public:
    int data;
    Node* next;
};


class LinkedList{
     Node* head;
public:
     LinkedList();

     LinkedList(const LinkedList& otherLinkedList){

          Node* iterator=otherLinkedList.head; //to iterate through the whole list and copy each node
          head=NULL;

          while(iterator->next!=NULL){
                insertAtintail(iterator->data); //extarct the element of node and give it to the function which will create a node and add it to the new list
                iterator=iterator->next;
          }
          insertAtintail(iterator->data);
     }

     void insertAtintail(int item){

          if(head==NULL){
              Node* temp=new Node;
              temp->data=item;
              temp->next=NULL;
              head=temp;
          }
          else{
              Node* tail=head;
              while(tail->next!=NULL)
                  tail=tail->next;
              Node* temp=new Node;
              temp->data=item;
              temp->next=NULL;
              tail->next=temp;
          }
      }

      void deleteHead(){

          if(head!=NULL){
                if(head->next!=NULL){
                    Node* toDelete=head;
                    head=head->next;
                    delete toDelete;
                }
          else{
                delete head;
                head=NULL;
          }
         }
      }

};

user3834119
  • 411
  • 9
  • 21
  • 1
    `otherLinkedList` doesn't even exist. The parameter is `otherList`. *Post real code.* – WhozCraig Nov 22 '14 at 08:26
  • 1
    It's best to post an [MCVE](http://stackoverflow.com/help/mcve). You need an `operator=` function too. I suspect that's what's tripping you up. – R Sahu Nov 22 '14 at 08:28
  • @RSahu Do we always have to overload assignment operator, whenever we overload copy constructor? – user3834119 Nov 22 '14 at 08:32
  • BTW, the copy constructor will run into problems if `otherLinkedList` is empty. – R Sahu Nov 22 '14 at 08:33
  • Your code also invokes *undefined behavior* copying an *empty* list to a new list. `iterator` is dereferenced when-NULL. – WhozCraig Nov 22 '14 at 08:33
  • @user3834119, yes. Checkout http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three. – R Sahu Nov 22 '14 at 08:33
  • Your `insertAtintail()` function doesn't set `tail` to `temp` at the end. – David G Nov 22 '14 at 15:41

0 Answers0