In the programming assignment, I need to clone a linked list (its a copy constructor so not returning anything but cloning). The old linked list will be going through some removing and adding elements but the new cloned linked list should remain untouched. How do I do that? When I remove and add new nodes to the old list, it also does the same for the new linked list. How can I avoid this?
this->head = other.head;
this->head->val = other.head->val;
SNode *curr = other.head->next;
SNode *newCurr = nullptr;
while (curr != nullptr) {
newCurr = curr;
curr = curr->next;
}
}
I have tried the above code, but when I modify the old list, ie, adding and removing nodes, it also adds and removes nodes from the new list. What can I do to avoid the modifications happening on the new list?
Your code is not creating new nodes, so this cannot work. A cloned list should consist of new nodes, so the
SNodeconstructor should be called.For instance:
This will just make the new list point to the same list: now you have two
headpointers pointing to the same head node. And then, by consequence, the following assignment doesn't do anything useful, as it really is assigning a member's own value to itself:The loop isn't doing anything useful either, as it is not assigning anything to any member that belongs to the new structure. It only assigns to variables, walking through the original list with two variables, where
newCurrfollows one step behindcurr.Here is a correction of your snippet:
This assumes you have an
SNodeconstructor that takes a single argument for the node's value.