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;
}
}
}
};