I tried to create a very basic linked list using dynamic memory allocation.You can add elements and traverse the list.But I seem to be having problems while writing the destructor of the program(getting segmentation fault).
I instead took the code from my destructor and then put it in a member function called purge() which did not generate any errors.Why is this?
Is there something fundamentally wrong with my class?
#include <iostream>
struct LList
{
LList *p , *s;
int data;
LList (LList *prev , LList *succ, int n) : p{prev} , s{succ} , data{n}{}
~LList()
{
auto start = this;
while (start->p ) start = start->p;
while(1)
{
auto temp = start;
start = start->s;
delete temp;
if (start == nullptr) break;
}
std::cout << "Destruted!";
}
void traverse() const
{
auto start = this;
while (start->p != nullptr)start = start->p;
while (1)
{
std::cout << start->data;
if (start->s == nullptr) break;
else start = start->s;
}
}
};
int main()
{
LList *natural = new LList{nullptr , nullptr , 1};
natural = new LList{natural, nullptr , 2};
natural->p->s = natural;
natural = new LList{natural, nullptr , 5};
natural->p->s = natural;
natural->traverse();
std::cout << natural->data;
natural->~LList();
}
Version with Purge:
#include <iostream>
struct LList
{
....
void purge()
{
auto start = this;
while (start->p ) start = start->p;
while(1)
{
auto temp = start;
start = start->s;
delete temp;
if (start == nullptr) break;
}
std::cout << "Destruted!";
}
void traverse() const
{
auto start = this;
....
int main()
{
...
natural->purge();
}
p.s : Does even purge do the trick ? I can still go:
natural->purge();
std::cout << natural->data;
}
towards the end and it would output 125Disrupted!5