I am required to create a recursive worker function to create a deep copy of a singly linked list in C++, containing key-item pairs. It passes tests when I use the deepdelete deconstructor, but when I attempt to test by copying using a deep copy constructor, I get errors in the lookup() function.
The below is what I have so far:
Deconstructor:
Dictionary::~Dictionary()
{
deepDelete(head);
}
Copy constructor:
Dictionary::Dictionary(const Dictionary & org)
{
this->head = deepCopy(org.head);
}
Deep delete recursive worker function:
void Dictionary::deepDelete(Node* current)
{
if (current == NULL)
{
return;
}
else
{
deepDelete(current->next);
delete current;
}
}
Copy constructor recursive worker function:
Dictionary::Node* Dictionary::deepCopy(Node* org)
{
if (org == NULL)
{
return nullptr;
}
else
{
Node* headc = new Node;
headc->k = org->k;
headc->i = org->i;
if (org->next != NULL)
{
//I have tried both of these, which produce the same error
headc->next = org->next;
//headc->next = deepCopy(org->next);
}
return headc;
}
return nullptr;
}
Lookup function (Error here):
Dictionary::Item* Dictionary::lookup(Key k)
{
Node *temp = head;
while (temp != NULL)
{
//Exception thrown: read access violation.
temp was 0x10.
if (temp->k == k)
{
return &temp->i;
}
temp = temp->next;
}
return nullptr;
}
Insert function:
bool Dictionary::insert(Key k, Item i)
{
if (lookup(k) == nullptr)
{
Node *temp = new Node;
temp->k = k;
temp->i = i;
temp->next = NULL;
if (head == nullptr)
{
head = temp;
tail = temp;
temp = NULL;
}
else
{
tail->next = temp;
tail = temp;
}
return true;
}
else
{
return false;
}
}
.h file (As requested:
#pragma once
#include <string>
#include <string.h>
using namespace std;
class Dictionary
{
public:
using Key = std::string;
using Item = std::string;
Dictionary()
{
head = nullptr;
tail = nullptr;
};
~Dictionary();
Dictionary(const Dictionary &);
Item* lookup(Key);
bool insert(Key, Item);
bool remove(Key);
private:
struct Node
{
Key k;
Item i;
Node *next;
};
Node* head;
Node* tail;
static void deepDelete(Node*);
static Node* deepCopy(Node*);
static Item* lookupRec(Key, Node*&);
static bool insertRec(Key, Item, Node*&);
static bool removeRec(Key, Node*&);
};
The deep delete and copy functions must be recursive and must be deep. I have to use a singly linked list and cannot use std::list. I am fairly sure the problem is in deepcopy but I cannot figure it out for the life of me.