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 SNode
constructor should be called.
For instance:
this->head = other.head;
This will just make the new list point to the same list: now you have two head
pointers 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:
this->head->val = other.head->val;
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 newCurr
follows one step behind curr
.
Here is a correction of your snippet:
// Deal with boundary case: empty list
this->head = NULL;
if (other.head == NULL) return; // Nothing more to do.
// Clone the head node
this->head = new SNode(other.head->val);
SNode *curr = other.head->next;
SNode *tail = this->head; // tail is a more descriptive name
while (curr != nullptr) {
tail->next = new SNode(curr->val); // Clone current node and append it
tail = tail->next; // This new node is now the tail
curr = curr->next;
}
This assumes you have an SNode
constructor that takes a single argument for the node's value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.