Do you have any idea what can I do wrong? |
There's an infinite number of things you can do wrong. The world is your oyster! :)
Within your "(head != nullptr)" branch in your insert function, you never allow for the opportunity for the head pointer to be updated.
The quick fix way would be to add another branch for if head != nullptr && (number being inserted < head's number).
There
is a more eloquent solution one could find, using a pointer-to-pointer or reference-to-pointer. Perhaps if you wanted a challenge, you could explore this.
Some other stuff:
In the code you have shown,
1 2 3 4 5
|
if(head == nullptr){
}else if(head != nullptr){
}
|
That "else if" can just be an "else".
______________________________
1 2 3
|
Node* it = head;
while(it->next != nullptr){
|
What happens here if head is null? What happens here if head is not null, but the next element is null? Will anything be printed? It seems you will always not print one of the nodes.
______________________________
1 2
|
Node* new_node = new Node;
if(new_node){
|
This check is redundant. If the call to new were to fail, it would throw a bad allocation exception.
______________________________
Fix, part 1:
Change your printing logic:
1 2 3 4 5 6 7 8
|
Node* it = head;
while(it != nullptr){
std::cout << "Country: " << it->name << ", population: " << it->num << " million\n";
it = it->next;
}
|
Fix, part 2.
< Edit: I removed it, because there is still a bug in the else part of the code, so my solution was wrong. Just look at dutch's code >