【问题标题】:What does Node * head outside of the struct do?Node * head 在结构之外做什么?
【发布时间】:2019-10-14 10:56:28
【问题描述】:

所以我有类 LinkedList。有人可以解释为什么 node * head 在结构之外,而 node * next, prev 在结构内吗?这样做的目的是什么,它与其他人有何不同?谢谢

class LinkedList
{
public:
        LinkedList();
        ~LinkedList();

        void add(char ch);
        bool find(char ch);
        bool del(char ch);
        void display(
private:
        struct node
        {
                char data;
                node * next;
                node * prev;          
        };
        node *head;
};

【问题讨论】:

  • 我认为您应该重新阅读您正在使用的任何书籍中有关链接列表的部分。或者在您对此不了解的地方更明确一点。
  • 要访问第一个元素,您需要头部。请记住,整个类都是您的 LinkedList,而不仅仅是结构。 struct只是LinkedList中的一个元素,它指向前一个元素和下一个元素(因此是一个双链表)并包含数据
  • head 不是struct node 定义的一部分。每个节点都没有自己的headhead 是一个指向 struct node 实例的指针,表示指向由 0 个或多个节点组成的链表的指针。
  • 看代码。 LinkedList 的构造函数可能看起来类似于:LinkedList::LinkedList() : head(nullptr) {},然后看看 add() 中发生了什么。

标签: c++ struct linked-list


【解决方案1】:

这个

    struct node
    {
            char data;
            node * next;
            node * prev;          
    };

是类中结构类型的内部声明。

这个

node *head;

是类LinkedListstruct node * 类型的数据成员的声明。为了更清楚,用以下方式重写列表定义

struct node
{
        char data;
        node * next;
        node * prev;          
};

class LinkedList
{
public:
        LinkedList();
        ~LinkedList();

        void add(char ch);
        bool find(char ch);
        bool del(char ch);
        void display(
private:
        node *head;
};

将类定义中的结构声明为私有声明,使得结构类型对链表的用户不可见。

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多