为链表C++创建节点

Create Node for linkedlist C++

本文关键字:节点 创建 C++ 链表      更新时间:2023-10-16

我正在使用c++实现链表。我在LinkedList.h中创建了一个结构Node,并试图重载节点中的运算符。但当我编译时,我得到了这个错误代码:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
class LinkedList{
typedef struct Node{
    int data;
    Node* next;
} * nodePtr;
//Returns true if the current Node object value is 
//less than the parameter Node object value 
bool operator < (const Node& node) const {
    return this->data < node->data;          <--- Unable to resolve identifier data.
};
#endif  /* LINKEDLIST_H */

我不知道我做错了什么。有人能告诉我吗?!谢谢

尽管我会用不同的方法来做这件事,但问题是您没有在类中定义任何位置来容纳Node结构。我不确定你是否在尝试:

class LinkedList{
    typedef struct Node{
        int data;
        Node* next;
    } * nodePtr;
    Node node; // Added this
    //Returns true if the current Node object value is
    //less than the parameter Node object value
    bool operator < (const Node& node) const {
        return this->node.data < node.data;
    }
};

看起来您正在尝试访问不存在的东西。您的LinkedList实现没有名为data的变量。

最简单的修复方法是更改operator主体:

return this->nodePtr->data < node->data;

然而,我建议重构为Node提供一个完全独立的类;您可以将运算符重载放在该类中。

您将节点作为引用传递,因此应该使用node.data

还删除关键字typedef,因为它使您只定义类型,并且您的列表确实需要指向第一个节点的指针!

然后您必须将您的退货更新为:

return this->nodePtr->data < node.data;