Skip to main content

Section 27.12 Copying

Now that we have a way to add nodes to the end of the list efficiently, making a copy of another list becomes much easier. We can simply iterate through the nodes of the source list and use our existing insertEnd method to add each nodeโ€™s data to the new list.
We will likely want to use this logic in multiple places, so it makes sense to put it in a helper function. copyFrom will take another list as its parameter and add all of the nodes from that list to the current list. Here is what the logic looks like :
LinkedList::copyFrom(LinkedList source) {
    Node* sourceCur = source.head
    while (sourceCur != nullptr) {
        value = sourceCur->data
        insertEnd(value)
 	      sourceCur = sourceCur->next
    }
}
With this helper function in place, we can implement both the copy constructor and the copy assignment operator easily by calling copyFrom.
The copy constructor simply needs to make sure head, tail and size are all initialized (if not already done in their declarations), and then call copyFrom with the other list as the argument.
Listing 27.12.1.
template <typename T>
LinkedList<T>::LinkedList(const LinkedList<T>& other) {
    head = nullptr;
    tail = nullptr;
    size = 0;
    copyFrom(other);
}
As usualy, an assignment operator needs to worry about self-assignment and clean up any existing data before copying from the other list. Checking for self assignment can be done in the same way as we did for an array based list by comparing the address of this list (the one being assigned to) with the address of the other list (the one being assigned from). To remove any existing data, we can call our clear method to delete all the nodes in the current list.
Listing 27.12.2.
template <typename T>
LinkedList<T>& LinkedList<T>::operator=(const LinkedList<T>& other) {
    if (this == &other) {
        return *this; // Handle self-assignment
    }
    clear();  // remove existing nodes, reset head, tail, size
    copyFrom(other);
    return *this;
}
You have attempted of activities on this page.