I wrote a simple implementation of doubly linked list in C++ using templates. However, I have some problems with copy constructor and assignment operator. My code gives me segmentation fault and I don't know how to fix it and where is the error (the problem is with copy constructor and assignment operator):
#include <iostream>
using namespace std;
template <class T>
class MyNode
{
public:
MyNode(const T &e = T(), MyNode *n = NULL, MyNode *p = NULL) : element(e), next(n), previous(p) {}
~MyNode() {}
T element;
MyNode *next;
MyNode *previous;
};
template <class T>
class MyList
{
private:
MyNode<T> *head;
MyNode<T> *tail;
public:
MyList()
{
head = new MyNode<T>();
tail = new MyNode<T>();
}
~MyList()
{
clear();
delete head;
delete tail;
}
MyList(const MyList& otherList)
{
while (otherList.head->next!=NULL)
{
MyNode<T> *curr = otherList.head->next;
insertLast(curr->element);
otherList.head->next = curr->next;
}
}
MyList& operator=(const MyList& otherList)
{
if(this == &otherList)
return *this;
while (otherList.head->next!=NULL)
{
MyNode<T> *curr = otherList.head->next;
insertLast(curr->element);
otherList.head->next = curr->next;
}
return *this;
}
bool isEmpty()
{
return (head->next == NULL);
}
void insertFirst(const T &e)
{
if (isEmpty())
{
MyNode<T> *newNode = new MyNode<T>(e);
head->next = newNode;
tail->previous = newNode;
}
else
{
MyNode<T> *actualFirst = head->next;
MyNode<T> *newNode = new MyNode<T>(e, actualFirst);
actualFirst->previous = newNode;
head->next = newNode;
}
}
void insertLast(const T &e)
{
if (isEmpty())
{
MyNode<T> *newNode = new MyNode<T>(e);
head->next = newNode;
tail->previous = newNode;
}
else
{
MyNode<T> *actualLast = tail->previous;
MyNode<T> *newNode = new MyNode<T>(e, NULL, actualLast);
actualLast->next = newNode;
tail->previous = newNode;
}
}
bool remove(MyNode<T> *r)
{
if (isEmpty())
{
return false;;
}
MyNode<T> *removeNode = tail->previous;
while (removeNode!=NULL)
{
if (removeNode==r)
{
break;
}
removeNode = removeNode->previous;
}
if (removeNode==NULL)
{
return false;
}
else
{
MyNode<T> *afterRemove = removeNode->next;
MyNode<T> *beforeRemove = removeNode->previous;
if (afterRemove==NULL)
{
tail->previous = beforeRemove;
}
else
{
afterRemove->previous = beforeRemove;
}
if (beforeRemove==NULL)
{
head->next = afterRemove;
}
else
{
beforeRemove->next = afterRemove;
}
delete removeNode;
return true;
}
}
void clear()
{
while (tail->previous!=NULL)
{
MyNode<T> *remove = tail->previous;
tail->previous = remove->previous;
delete remove;
}
}
void show()
{
while (head->next!=NULL)
{
MyNode<T> *curr = head->next;
std::cout << curr->element << "\n";
head->next = curr->next;
}
}
};
int main()
{
MyList<int> l1;
l1.insertLast(1);
l1.insertLast(2);
l1.insertLast(3);
//l1.show();
MyList<int> l2(l1);
//l2 = l1;
l2.show();
return 0;
}