链表:结构内的结构?

时间:2021-02-08 04:46:41

标签: c++ pointers data-structures linked-list structure

在使用 C++ 中的链表方面,我还是个新手。我正在翻阅我的教科书,在链表部分下找到了这个头文件。

//Specifcation file for the NumberList class
#ifndef NUMBERLIST_H
#define NUMBERLIST_H

class NumberList
{
private:
  //Declare a structure for the list
  struct ListNode
  {
     double value;         //The value in this node 
     struct ListNode *next;  //To point to the next node 
  };

  ListNode *head;      //List head pointer
public:
  //Constructor 
  NumberList();
   { head = nullptr; }

  //Destructor 
  ~NumberList();

  //Linked list operations
  void appendNode(double);
  void insertNode(double);
  void deleteNode(double);
  void displayList() const;
};
#endif

所以我想知道 struct ListNode *next; 它似乎是一个指针,那么为什么我们必须在这个指针上包含“struct”部分呢?一开始我很困惑,因为我认为它是另一个结构体内部的结构体。

有人可以向我解释一下吗?

1 个答案:

答案 0 :(得分:1)

<块引用>

所以我想知道 struct ListNode *next;

正如你后面提到的,它是一个指向 struct ListNode 的下一个块的指针。检查下图。 ListNode 在这里由 DataNext 组成。 Next 是指向下一个 ListNode 单元格的指针。

<块引用>

它似乎是一个指针,那么为什么我们必须在这个指针上包含“struct”部分?

它是 C-style 声明。在 C 中,struct 名称位于它们自己的命名空间中。在 C++ 中你不需要这个。您在这里看到它是因为 C++ 在这种情况下也支持 C-style 声明。你可以在这里查看我编辑过的代码。我从 ListNode 结构内的 struct 指针声明中删除了 next 部分,它工作正常。

#include <iostream>

using namespace std;

class NumberList
{
private:
  //Declare a structure for the list
  struct ListNode
  {
     double value;         //The value in this node 
     ListNode *next;  //To point to the next node 
  };

  ListNode *head;      //List head pointer
public:
  //Constructor 
  NumberList() { head = nullptr; }
  
  NumberList(double val) {
      head = new ListNode();
      head->value = val;
  }

  //Destructor 
  ~NumberList();

  //Linked list operations
  void appendNode(double);
  void insertNode(double);
  void deleteNode(double);
  void displayList() {
      ListNode *curr = head;
      while(curr != nullptr) {
          cout << curr->value << " ";
          curr = curr->next;
      }
      cout << endl;
  }
};

int main()
{
    NumberList *nl = new NumberList(5.0);
    nl->displayList();
    return 0;
}
相关问题