在这个节点定义中,为什么我们在结构定义之后使用"Node"?

In this node definition, why are we using the "Node" after the structure definition?

本文关键字:定义 之后 结构 Node 为什么 节点 我们      更新时间:2023-10-16
typedef struct node
{
 int data;
 struct node *next;
}Node;  // ???

我不明白为什么我们在定义后使用节点。执行什么功能?它是否阻止结构无限指向自身?这个问题可能听起来很愚蠢,因为我仍在学习。谢谢。

结构定义之后有一个Node,因为之前有一个typedef

结构定义本身是这样的:

struct node
{
  int data;
  struct node *next;
};

由于这是C++,因此足以通过名称来引用结构类型 node .然而,似乎编写它的人最初要么来自 C 背景,要么旨在提供与 C 兼容的标头。在 C 中,你必须将其称为 struct node ,有些人觉得很冗长。因此,相关人员立即提供了一个类型别名。您提供的代码等效于:

struct node
{
  int data;
  struct node *next;
};
typedef struct node Node;

它允许我们用名称来引用相同的类型 Node ,在 C 或 C++ 中。

在这里,您已经定义了一个结构,并同时声明了一个结构变量。 typedef关键字用于创建类型Node,其类型为 struct node

因此,您可以轻松地使用Node n1;而不是 struct node n1 .