I have a linked list class and I have trouble with two things:
- my copy assignment operator doesn’t copy the exact list
- I have no idea how to do the overloaded output with the linked list, I know how it works in basics, but I’m lost with my linked list.
UPDATE:
why is the copy assignment operator giving me reverse of my list?
list& list::operator =(const list &l){
while (p!=NULL)
del();
Node* current=l.p;
while(current!=NULL){
insert(current->x);
current=current->next;
}
when i have 10–2–NULL
It prints 2–10–NULL
At the end of your assignment operator you set
ptocurrentwhich must be a null pointer, or you wouldn’t have exited thewhileloop.pshould already be set by the previous calls toinsert.What happens if the list already has elements when you assign to it? Do you really want to append, or do you want to remove the existing elements first?
In your
printmember the loop runs untilqis NULL, then after it’s finished you test whetherqis NULL … of course it is. So you always print NULL after any list.In
mainyou have this, which destroys the list:So the next line is undefined behaviour, because you access an object that has already been destroyed, then the object goes out of scope again and its destructor runs, which is also undefined behaviour because the object has already been destroyed. You don’t need to call a destructor manually, that’s the whole point of destructors, they clean up automatically when the object goes out of scope.
Edit: Your assignment operator copies the list in reverse because you go through it in order but
insertputs each element at the start of the copied list, so you copy the first element, then put the second element before it, then put the third before that etc.To copy the list you need to put the copied elements in the same order, i.e. insert each one at the end not the beginning.