Please Note: This is for a homework assignment,
however it was due ~3 weeks ago and I'm only doing it for the learning aspect.
I'm learning about Singly linked lists online and I've gained a basic understanding of how to do them. However, when I was reading this tutorial:
https://www.codementor.io/codementorteam/a-comprehensive-guide-to-implementation-of-singly-linked-list-using-c_plus_plus-ondlm5azr
It had the following example to demonstrate how to delete a node from a particular position in the list:
1 2 3 4 5 6 7 8 9 10 11 12
|
void delete_position(int pos)
{
node *current=new node;
node *previous=new node;
current=head;
for(int i=1;i<pos;i++)
{
previous=current;
current=current->next;
}
previous->next=current->next;
}
|
I noticed that none of the lines delete the node. They just remove it from the list. Isn't this bad? So I was wondering how to delete the node rather than just removing it from the list, unless I'm misunderstanding this and it was deallocated from memory already.
I was thinking "delete previous->next;" may fix it if I were to add that after line 9. But I looked it up and "delete" will call the destructor and I don't have a destructor defined. So then I looked up about destructors and it said if you don't have a destructor defined, that's generally okay because it will create it's own,
however, if you are using pointers in a class or something then you need to declare your own. Which means I need to make my own destructor but after doing more research on destructors it seems I can only delete the things stored in the private: section of the class and not certain variables from member functions.
I think by now you've probably caught on that I'm thoroughly confused haha.
Basically, I have two questions.
1. Is the example code from the website link above okay? Or does it cause memory problems?
2. When using linked lists, do I need a user defined destructor and if so how do I make one properly?
I doubt you need to look at my code but if you do, then:
Main.cpp:
http://cpp.sh/9kekc
SinglyLinkedList.h:
http://cpp.sh/5e2asr
It's probably not great at the moment.
Main Sources:
https://www.codementor.io/codementorteam/a-comprehensive-guide-to-implementation-of-singly-linked-list-using-c_plus_plus-ondlm5azr
https://docs.microsoft.com/en-us/cpp/cpp/destructors-cpp?view=vs-2019
https://www.includehelp.com/cpp-tutorial/difference-between-delete-and-free.aspx
Help would be greatly appreciated, thanks!