如何创建一个同时包含列表的节点

How to make a node that would contain a list as well

本文关键字:包含 节点 列表 何创建 创建 一个      更新时间:2023-10-16

我搜索了很多关于这个主题的有用内容,但没有找到。我做了一个链接列表,运行良好。现在,作为一项任务,我需要将一些字典单词存储在一个文件"input.txt"中。有人提到,你必须使用二维链表来完成这项任务,即在链表的节点内制作另一个链表。这意味着链接列表的每个节点现在也将包含一个列表。这也可以用矢量来完成,但我想链表可能更有用。现在考虑代码。

//在list.h 中

template <class T>
struct ListItem
{
    T value;
    ListItem<T> *next;
    ListItem<T> *prev;
    ListItem(T theVal)
    {
        this->value = theVal;
        this->next = NULL;
        this->prev = NULL;
    }
};
template <class T>
class List
{
    ListItem<T> *head;
public:
    // Constructor
    List();
    // Destructor
    ~List();
}

我需要在节点内制作一个链表,所以在"Struct ListItem"中,我正在做这样的事情:

List<T> dictionary;

但它给出了一个错误:

"ISO C++ forbids declaration of âListâ with no type"

第二,如何开始在节点内创建另一个链表。我的意思是假设临时指针指向第一个链表的头。我现在该如何在这个节点内创建另一个节点(属于我的第二个链表)。我想可能是这样的:

temp->ListItem<T>* secondListNode = new ListItem<T>(item); // I don't know whether
//It would or not as I am stuck in the first part.

这必须使用二维格式来完成,所以请遵守限制条件。关于这个问题,任何其他有用的建议都会有所帮助。提前谢谢。

您有一个循环依赖项。如果在List<T>中只有一个指向ListItem<T>的指针,那么首先声明ListItem<T>,然后定义List<T>,再定义ListItem<T>类:

template<class T>
class ListItem;
template<class T>
class List
{
    ListItem<T> *head;
    // ...
};
template<class T>
class ListItem
{
    // `dictionary` is not a pointer or a reference,
    // so need the full definition of the `List<T>` class
    List<T> dictionary;
    // ...
};

当您参考字典时,您可能会考虑使用std::map。

例如:

std::map<std::string, std::list<std::string> >

如果您将值存储为std::string。

我不确定我是否完全理解你所说的"这意味着链接列表的每个节点现在也将包含一个列表"

如果你只想有一个字符串列表的列表,你可以很容易地用你现有的列表数据结构实例化它,这要归功于模板功能:

List<List<std::string> > listOfLists;

当然,你仍然可以拥有你的"1D列表":

List<std::string> otherList;

通常,根据本地需求调整数据结构是个坏主意,但应该尝试以更专业的方式使用通用数据结构,比如上面的"列表"。不要将"列表列表"实现为单独的类,也不要将常规列表更改为2D列表。它只是一个"任何类型的列表T",所以T也可以是一个列表(一次又一次…)