Reputation: 13
I'm reading Lospinoso's "C++ Crash Course" and in it is the following code. I'm unsure of the reason behind the line "new_element->next = next." If I delete it the code still produces the same result.
When "&trooper2" is passed to the insert_after method, does the "next" pointer of trooper2 point where the "next" pointer of trooper1 pointed? Why assign the next pointer of trooper2 to the next pointer of trooper1 when they're both already null pointers?
Happy Holidays all and thank you for your help
#include <cstdio>
struct Element {
Element* next{};
void insert_after(Element* new_element) {
new_element->next = next;
next = new_element;
}
char prefix[2];
short operating_number;
};
int main() {
Element trooper1, trooper2, trooper3;
trooper1.prefix[0] = 'T';
trooper1.prefix[1] = 'K';
trooper1.operating_number = 421;
trooper1.insert_after(&trooper2);
trooper2.prefix[0] = 'F';
trooper2.prefix[1] = 'N';
trooper2.operating_number = 2187;
trooper2.insert_after(&trooper3);
trooper3.prefix[0] = 'L';
trooper3.prefix[1] = 'S';
trooper3.operating_number = 005;
for (Element* cursor = &trooper1; cursor; cursor = cursor->next) {
printf("Storm Trooper %c%c-%d\n", cursor->prefix[0], cursor->prefix[1],
cursor->operating_number);
}
Upvotes: 1
Views: 85
Reputation: 1514
What this code does is insert an element between the calling element and the element it points to. Let's see whats happening:
= trooper1 > NULL
= trooper1 > trooper2 > NULL
= trooper1 > trooper2 > trooper3 > NULL
You are inserting an element between the calling element and next which was already NULL. So you're setting the new element's next to NULL as well.
** Update **
Like @Beta said, if you'd keep on adding to the first element, you'd actually get a list in which new elements are inserted at the second place. The next element is than actually pointing at something:
= trooper1 > NULL
= trooper1 > trooper2 > NULL
= trooper1 > trooper3 > trooper2 > NULL
= trooper1 > trooper4 > trooper3 > trooper2 > NULL
Upvotes: 1
Reputation: 99172
In this example, the new_element->next = next;
makes no difference, because both pointers are null before (and after) the execution of the function. But if you try this:
...
trooper1.insert_after(&trooper3);
...
trooper1.insert_after(&trooper2);
...
you'll see a difference. With that line, the output will look the same as in the first example. Without that line, trooper3
will be lost.
Upvotes: 1