如何创建一个同时包含列表的节点
How to make a node that would contain a list as well
我搜索了很多关于这个主题的有用内容,但没有找到。我做了一个链接列表,运行良好。现在,作为一项任务,我需要将一些字典单词存储在一个文件"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
也可以是一个列表(一次又一次…)
- 反向给定链表中的K节点
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- 包含具有无效位置的节点引用的方式
- 节点构建失败。无法在包含目录的子目录中找到库头文件
- Boost::p tree - 访问列表中包含的属性树节点
- 如何在 main 中使用包含对节点的引用调用函数
- 打印与BST的直径相对应的节点所包含的路径
- 如何将XML文件拆分为多个XML,以便每个新文件只包含原始文件中的一个文本节点
- 创建包含节点的链接列表C++
- 包含一个图形节点作为关键字的无序映射
- 对包含多个元素的节点的链表进行排序
- 如何:给定文件描述符,获取包含文件的设备的设备节点
- 如何创建一个同时包含列表的节点
- vs2015 上的 stl 列表性能不佳,同时删除包含迭代器到自身在列表中的位置的节点
- 包含节点析构函数的列表
- 包含节点的简单单链表复制构造函数