jeudi 22 février 2018

Guidance for implementing a Copy Constructor into a Doubly Linked List Class

I have been attempting to implement a copy constructor, that creates a deep copy, for a doubly linked list class. I have been running into the issue where the head and tail the push_back() function attempts to operate on are undefined or a nullptr. If anyone has any experience with doubly linked list, please feel free to give any help.

My Copy Constructor function:

//copy constructor
DoubleLinkedList::DoubleLinkedList(const DoubleLinkedList& dll)
{
    copyList(dll);
}

My copyList function definition:

void DoubleLinkedList::copyList(const DoubleLinkedList& listToBeCopied)
{
    if (listToBeCopied.head == head) //checks to make sure that the list that is being copied isn't the same as the one it is copying to
    {
        return;
    }
    listToBeCopied.resetIterator(); //sets the iterator to head
    while (listToBeCopied.hasMore()) //continues to run as long as iterator is not equal to a nullptr (tail->next).
    {
        push_back((listToBeCopied.next())); //takes the data from the iterator and pushes it to the back of the list.
    }
}

My push_back() function defintion:

// insert str at back of list
void DoubleLinkedList::push_back(const AMString& str)
{
    Node *temp = new Node(str);
    if (head == nullptr)
{
    head = tail = temp;
    head->prev = nullptr;
    //cout << "\"" << str << "\" was added to the front and back (push_back).\n\n";
}
else
{
    temp->prev = tail;
    tail->next = temp;
    tail = temp;
    //cout << "\"" << str << "\" was added the back.\n\n";
}
count++;

}

Aucun commentaire:

Enregistrer un commentaire