Just beginning with C++ (be gentle, please). I have some code and I have to:
Code
I tried the following:
#include <cstdio>
struct Element {
Element* next{};
Element* previous{};
void insert_after(Element* new_element) {
new_element -> previous = this;
new_element -> next = this -> next;
this -> next = new_element;
}
void insert_before(Element* new_element) {
new_element -> previous = this -> previous;
new_element -> next = this;
this -> previous = new_element;
}
char prefix[2];
short operating_number;
};
int main() {
Element trooper1, trooper2, trooper3, trooper4;
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_before(&trooper3);
trooper3.prefix[0] = 'L';
trooper3.prefix[1] = 'S';
trooper3.operating_number = 005;
trooper3.insert_before(&trooper4);
trooper4.prefix[0] = 'F';
trooper4.prefix[1] = 'K';
trooper4.operating_number = 2602;
for (Element *cursor = &trooper1; cursor; cursor = cursor -> next) {
printf("stormtrooper %c%c-%d\n",
cursor->prefix[0],
cursor->prefix[1],
cursor->operating_number);
}
for (Element *cursor = &trooper3; cursor; cursor = cursor -> previous) {
printf("stormtrooper %c%c-%d\n",
cursor->prefix[0],
cursor->prefix[1],
cursor->operating_number);
}
}
It's very basic, I know. But I'm starting to learn. The code compiles correctly but I get this output:
/home/facundo/Escritorio/C++Projects/cmake-build-debug/C__Projects
stormtrooper TK-421
stormtrooper FN-2187
stormtrooper LS-5
stormtrooper FK-2602
stormtrooper TK-421
Process finished with exit code 0
I really don't understand why it prints only that (I guess there should be 8 lines of output). I was expecting an output that would print the elements like this:
trooper1
trooper4
trooper3
trooper2
trooper2
trooper3
trooper4
trooper1
Some help would be really appreciated. Thanks for taking your time.
In your insert
functions, you are not linking up all the pointers correctly:
void insert_after(Element* new_element) {
new_element -> previous = this;
new_element -> next = this -> next;
this -> next = new_element;
if (new_element -> next) // this check needed
// to correctly link the next -> previous
new_element -> next -> previous = new_element;
}
and
void insert_before(Element* new_element) {
new_element -> previous = this -> previous;
new_element -> next = this;
this -> previous = new_element;
if (new_element -> previous) // this check needed
// to correctly link the previous -> next
new_element -> previous -> next = new_element;
}
Also, in the second for
loop, note that trooper2
is the last Element
in the list, not trooper3
, so you need to start from there to see all the Element
s in reverse.
Here's a demo.