创建自己的链表时出错

Error while creating own linked list

本文关键字:出错 链表 自己的 创建      更新时间:2023-10-16

我正在尝试创建一个程序,该程序从文本文件中读取并将单词存储到单向链表中。我应该创建自己的链表,而不是使用 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文件中。