I've created a linked list template class which contains a copy constructor that performs a deep copy of the list.
LinkedList.hpp
template <class T>
class LinkedList {
protected:
struct Node {
T value;
Node *next;
Node(T val, Node *nxt=NULL) {
value = val;
next = nxt;
}
};
Node *head;
public:
LinkedList();
LinkedList(LinkedList &obj);
~LinkedList();
};
LinkedList.cpp
template <class T>
LinkedList<T>::LinkedList() {
head = NULL;
}
template <class T>
LinkedList<T>::LinkedList(LinkedList &obj) {
if (obj.head == NULL) {
head = NULL;
}
else {
head = new Node(obj.head->value);
Node *current = head;
Node *objHead = obj.head;
Node *currentObj = objHead;
while (currentObj->next != NULL) {
current->next = new Node(currentObj->next->value);
currentObj = currentObj->next;
current = current->next;
}
}
}
template <class T>
LinkedList<T>::~LinkedList() {
Node *current = head;
while (current != NULL) {
Node *garbage = current;
current = current->next;
delete garbage;
}
}
template class LinkedList<int>;
template class LinkedList<double>;
template class LinkedList<bool>;
template class LinkedList<string>;
From what I can tell, the default copy constructor implements this functionality naturally, but I wanted to see if I could create a deep copy of a linked list myself using a self-defined copy constructor.
When I test this using:
LinkedList<int> ll;
ll.add(1);
ll.add(2);
ll.add(3);
ll.add(4);
LinkedList<int> ll2 = ll;
ll.add(5);
ll.displayList();
ll2.displayList();
It prints 1,2,3,4,5
and then 1,2,3,4
. I believe this is correct. Are there any improvements I can make to the implementation of this?