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

时间:2013-02-15 12:07:22

标签: c++ linked-list doubly-linked-list

我搜索了很多内容以找到关于这个主题的有用内容但是重新开始。我已经制作了一个工作正常的链表。现在,作为一个分配,我需要存储一些文件中给出的字典单词" input.txt"。提到您必须使用2-D链接列表执行此分配,即在链接列表的节点内创建另一个链接列表。这意味着链表的每个节点现在也包含一个列表。这可以用向量完成,但我想链表可能更有帮助。 现在考虑代码。

//在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();
}

我需要在节点内创建一个链表,所以在&#34; Struct ListItem&#34;我正在做这样的事情:

List<T> dictionary;

但它给出了一个错误:

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

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

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.

这必须使用二维格式完成,所以请坚持约束。关于这个问题的任何其他有用的建议都会有所帮助。 提前谢谢。

3 个答案:

答案 0 :(得分:1)

你有一个循环依赖。如果ListItem<T>中只有指向List<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;

    // ...
};

答案 1 :(得分:0)

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

例如:

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

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

答案 2 :(得分:0)

我不确定我是否完全理解你的意思“这意味着链表的每个节点现在都包含一个列表

如果您只想拥有字符串列表列表,可以使用现有的List数据结构轻松实例化,这要归功于模板功能:

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

当然,您仍然可以拥有“1D列表”:

List<std::string> otherList;

通常,将数据结构调整为本地需求是一个坏主意,而是尝试以更专业的方式使用通用数据结构,例如“列表列表”之上。不要将“列表列表”实现为单独的类,也不要将通用列表更改为2D列表。它只是一个“任何类型的T列表”,因此T也可以再次列出一个列表(又一次又一次......)。