通过自定义结构和链接列表类在C ++中使用哈希表

时间:2018-04-23 21:05:09

标签: c++ linked-list

我正在尝试通过从.txt文件中读取字典来在C ++中创建拼写检查程序。我的阅读功能完全正常,我遇到的问题是当我尝试导航并添加到我的链接列表时。

当我尝试将要添加的最新节点的指针设置为头指针的值时,我收到一条错误,指出没有可行的从“节点”转换为“节点*”。

执行此转换的最佳方式是什么。

我已经尝试过转动'节点头';在我的链表类内部指向一个但收到相同的错误。

首先,我创建了我的Node结构(在头文件中声明)

struct Node
{

private:
    std::string word;
    Node *nextNode;

public:
    //Default constructor
    Node();
    ~Node();

    //My Setters and getters for the class
    void setWord(std::string _word) { word = _word; }
    std::string getWord() { return word; }
    void setNode(Node *_nextNode) { nextNode = _nextNode; }
    Node getNode() { return *nextNode; }

};

后面是我的LinkedList类(也在头文件中声明)

class LinkedList
{

private:
    Node head;
    int listSize;

public:
    LinkedList();
    ~LinkedList();

    void setListSize(int _listSize) { listSize = _listSize; }
    int getListSize() { return listSize; }
    void setHead(Node _head) { head = _head; }
    Node getHead() { return head; }

    //Function that adds the next node to the head
    void addToHead(LinkedList &myList, Node &myNode);

};

继承我的职能

void LinkedList::addToHead(LinkedList &myList, Node &myNode)
{

    myNode.setNode(myList.getHead().getNode());
    //Here is where I'm getting my error
    //"No viable conversion from 'Node' to 'Node *'

    myList.setHead(myNode);

}

1 个答案:

答案 0 :(得分:0)

LinkedList课程不应该拥有第一个Node

成员head应为Node*宽度默认值nullptr(列表为空)。 listSize也应该指定一个默认值。

LinkedList() head(nullptr), listSize(0) {};

修改

我个人会避免强制外部代码来管理单个节点。 保持与实现无关的接口。

class LinkedList
{

private:
    Node *head_;
    int size_;

public:
    LinkedList();
    ~LinkedList();
    int size() const { return listSize; }
    // insert after the i-th element
    void insert(std::size index, std::string const& word);
    // return the i-th element
    std::string &at(std::size index);
    std::string const &at(std::size index) const;
    // removes the i-th element
    void remove(size::size index);
};

通过这种方式,您可以将所有列表操作代码集中到LinkedList类中。

您还应该考虑与复制LinkedList对象相关的问题。