创建自己的链表时出错
Error while creating own linked list
我正在尝试创建一个程序,该程序从文本文件中读取并将单词存储到单向链表中。我应该创建自己的链表,而不是使用 STL。我尝试查找相当数量的教程,但我不断收到变量"head"的错误。它说"节点的值类型不能用于初始化节点类型的实体"
这是列表.cpp:
#include "List.h"
#include "Node.h"
#include <iostream>
using namespace std;
void List::add(string s){
Node* newNode = new Node();
newNode->addString(s);
newNode->setNext(NULL);
Node *temp = head;
if(temp != NULL)
{
while(temp->Next() != NULL)
{
temp = temp->Next();
}
temp->setNext(newNode);
}
else
{
head = newNode;
}
}
void List::print(){
Node *temp = head;
if(temp == NULL)
{
cout<<"EMPTY"<< endl;
return;
}
if(temp->Next() == NULL)
{
cout<<temp->Word();
cout<< "-->";
cout<< "NULL" << endl;
}
else
{ do{
cout<<temp->Word();
cout<<"-->";
temp = temp->Next();
}
while( temp != NULL);
cout << "NULL" << endl;
}
}
void List::read(ifstream& fin){
while(!fin.eof())
{
fin>>sTemp;
add(sTemp);
}
}
这是节点.h
using namespace std;
#include <string>
class Node
{ string val;
Node* next;
public:
Node(void){}
Node(string s)
{
val = s;
next = nullptr;
}
void addString(string aString){ val = aString;};
void setNext(Node* aNext){next = aNext;};
string Word(){return val;};
Node* Next(){return next;};
string sTemp;
};
这是列表.h
#include <string>
#include <fstream>
#include "Node.h"
using namespace std;
class List{
Node* head;
public:
List()
{
head = NULL;
}
void print();
void add(string s);
void find(string key);
void read(ifstream& fin);
string sTemp;
}
在实际的List.cpp下,当我说节点*temp = head时,它给了我一个错误;带有上述错误。任何原因为什么以及如何解决这个问题?
这里的部分问题是,在List.cpp
中,您已经包含Node.h
两次。
- 直接包含List.h,它本身包括Node.h
- 直接包括 Node.h
我很惊讶编译器没有警告你这一点。 相反,它似乎选择重新定义Node
因此您最终会得到两个不兼容的Node
值。 您需要在头文件中添加包含保护以防止双重包含
列表.h
#if !LIST_H
#define LIST_H
...
#endif
节点.h
#if !NODE_H
#define NODE_H
...
#endif
另请注意,一般来说,在头文件中包含using
语句被认为是不好的做法。 而是在标头中使用命名空间限定名称,并将 using
语句放入.cpp文件中。
相关文章:
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 将链表转换为指针数组时出错
- 合并两个排序链表时运行时出错
- 使用链表实现堆栈时出错
- 尝试删除链表的头部或中间节点时出错
- 创建自己的链表时出错
- 添加两个数字(链表中的数字)时出错
- 在C++中实现双链表时出错
- 链表实现中出错
- 分段 删除链表的项目时出错
- 数据类型匹配,但我的链表仍然出错
- 解析链表时出错
- 使用链表将中缀转换为后缀时出错
- 将单词插入链表时出错
- 在链表的开头插入时读取内存时出错
- 我的C++代码使用链表时出错
- 在链表的insert last函数中交换两行时出错
- c++:尝试从链表中的第二个节点(虚拟节点)开始打印时出错
- EXC_BAD_ACCESS使用链表时出错
- 我的堆栈使用链表时出错.无法打印数字循环.(C++)