如何制作一个函数来解决双向链表节点?

How to make a function to adress doubly linked list node?

我在 C++ 中将双向链表实现为 class

在 main.cpp 中,我将其他 class 的对象推入此列表,如下所示

list.insertBack(ClassA(name, description));

但之后我需要更改此对象的某个字段,例如执行更改人口的方法。为此,我需要以某种方式从列表中找到这个对象,就像我对常规数组所做的那样(smth 就像 a[i])。为此,我需要在我的列表 class 中添加一个特殊的 method/function。我该如何实施?

您只需为您的 class 提供 operator[]:

template<class T>
class List {

    // your private interface

public:

    // your other public interface 

    T& operator[](unsigned int i)
    {
        Node* n = this->head;
        for (; i>0; --i)
        {
            n = n->next;
        }
        return n->data;
    }
};

在您的 main 中,您可以像这样简单地使用它

int main() {
    List<double> l;
    l.insertBack(0.0);
    l.insertBack(1.0);
    l.insertBack(2.0);
    l.insertBack(3.0);

    std::cout <<  l[2] << std::endl;
}

请注意,您可能还需要此函数的 const 版本。这里有一个demo.

注意: 正如@Botje 所指出的,您可能还想对输入进行一些健全性检查。如果 i 等于或大于现有节点的数量,我的代码片段会取消引用 nullptr 并且你会得到未定义的行为。