First of all, this is part of an assignment I'm currently trying to figure out. I'm trying to create a copy constructor that deep copies a given LinkedList. I have coded the LinkedList methods already.
Here's the necessary parts of the LinkedList.h file.
LinkedList.h
private:
struct node {
Val data;
node* next = nullptr;
};
typedef struct node* nodePtr;
nodePtr head = nullptr;
nodePtr current = nullptr;
nodePtr temp = nullptr;
};
The parameters are given: "LinkedList::LinkedList(const LinkedList & ll)" ll is the linked list to be copied. I first tested if there is a head in the linked list, if not then that means the linked list is empty. Then I copied the head from the old list to the new list. I then set the new current to the head in preparation for the while loop. Inside the while loop, I am copying the data of the current node as well as the pointer to the next node. At the end I set the next pointer to nullptr to signify the end of the new list.
LinkedList.cpp
LinkedList::LinkedList(const LinkedList & ll){
if (ll.head == nullptr) {
return;
}
head = ll.head;
current = head;
while (ll.current->next != nullptr) {
current->data = ll.current->data;
current->next = ll.current->next;
}
current->next = nullptr;
}
I'm not sure if this is deep copying or not. I also know that ll.current's starting position is not at the head. I tried ll.current = ll.head. However, since it is given that this function is const. I can't set it like that.
There is also another function given: LinkedList & LinkedList::operator=(const LinkedList & ll) { } That I suspect may be needed. I'm hoping it optional that I use this.
ll.headisnullptr. The reason is that you didn't initialize any of the members -- you justreturn. - PaulMcKenziecurrent->dataandcurrent->nextwithout changing wherecurrentpoints to. - Simon Kraemer