C ++声明双链表,用两个for循环遍历双向列表并打印

C++ declaring double-linked list, traverse list both ways with two for-loops and print

刚开始接触 C++(请温柔点)。我有一些代码,我必须:

代码

我尝试了以下方法:

#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);
    }
}

这是非常基础的,我知道。但我开始学习了。 代码编译正确但我得到这个输出:

/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

我真的不明白为什么它只打印那个(我猜应该有8行输出)。 我期待的输出会打印这样的元素:

士兵 1

骑兵4

骑兵3

士兵2

士兵2

骑兵3

骑兵4

士兵 1

如果能提供一些帮助,我们将不胜感激。感谢您抽出时间。

在您的 insert 函数中,您没有正确链接所有指针:

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; 
}

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;
}

此外,在第二个 for 循环中,请注意 trooper2 是列表中的最后一个 Element,而不是 trooper3,因此您需要从那里开始以反向查看所有 Element

这里是 demo