It's nothing special, a simple one-way linked list that has to be self-ordered as soon as you enter any element, I'm starting to do it but I can not get the nodes to link correctly. The problem is that I do not understand why the elements are destroyed by iterating them if they are all nodes that are outside the scope of the.
I'm confused, I need someone to explain to me.
struct Node {
int data;
Node *next;
Node() = default;
explicit Node(int val) : data{val}, next{} {}
~Node() = default;
};
int main() {
// declaring
auto *a = new Node{4};
auto *b = new Node{2};
auto *c = new Node{3};
auto *d = new Node{5};
auto *e = new Node{1};
// linking
a->next = b;
b->next = c;
c->next = d;
d->next = e;
// sorting
for (auto &it{a} ; it->next != nullptr; it = it->next) {
if (it->data < it->next->data) {
auto *tmp = new Node();
tmp->data = it->data;
tmp->next = it->next;
it = it->next;
it->next = tmp;
}
}
// printing
for (auto &it{a}; it != nullptr; it = it->next) {
std::cout << it->data << "\n";
}
return 0;
}