struct node *next; 是什么意思?在用c语言编写的链表程序中?

What is meant by struct node *next; in a linked list program made in c language?

// Linked list implementation in C

#include <stdio.h>
#include <stdlib.h>

// Creating a node
struct node {
  int value;


 struct node *next; //What is this, what are we doing here?
};

// print the linked list value
void printLinkedlist(struct node *p) {
  while (p != NULL) {
    printf("%d ", p->value);
    p = p->next;
  }
}

int main() {
  // Initialize nodes
  struct node *head;
  struct node *one = NULL;
  struct node *two = NULL;
  struct node *three = NULL;

  // Allocate memory
  one = malloc(sizeof(struct node));
  two = malloc(sizeof(struct node));
  three = malloc(sizeof(struct node));

  // Assign value values
  one->value = 1;
  two->value = 2;
  three->value = 3;

  // Connect nodes
  one->next = two;
  two->next = three;
  three->next = NULL;

  // printing node-value
  head = one;
  printLinkedlist(head);
}

我想问下这行代码是干什么的? 它在代码的创建节点部分(顶部)

struct node *next;

我们是否为 sturct node 分配了一个指针类型的结构变量,但它在同一结构内,在同一结构内分配了一个名为 *next 的变量?但这是不允许的,对吧?

我们可以在 } 之外和 ; 之间或 main() 中声明变量 只是代码的功能部分,不是吗?

喜欢

main()
{
struct node *next;
}

再次,然后我遇到一个 post 提到它作为指向结构本身的指针,任何人都可以解释我们如何在同一个结构中做到这一点?

next 成员指向 struct node 的另一个实例。在图形上,我们通常这样表示:

+–––––––+––––––+      +–––––––+––––––+  
| value | next |––––> | value | next |
+–––––––+––––––+      +–––––––+––––––+

struct 类型不能包含其自身的实例 - 我们不能创建类似

的类型
struct node {
  int value;
  struct node next;
};

有两个原因:

  • 类型定义在结束前不完整},不能创建不完整类型的实例;

  • 该类型需要无限存储(struct node 包含类型 struct node 的成员 next,后者包含类型 [=] 的成员 next 13=] 其中包含类型 struct node... 的成员 next);

但是,我们可以将 next 声明为指向 struct node 指针 ,因为我们可以创建指向不完整类型的指针。指针的大小和表示与其指向的类型的大小和表示无关。

什么意思

struct node *next; 被读作“next is a pointer to another struct node”。

这只是一个递归结构声明(定义):

struct node {
  int value;
 struct node *next; //What is this, what are we doing here?
};

表示一个节点由两部分组成:

  1. 一个整数值
  2. 指向另一个节点的指针。

linked lists 上的 wiki 文章有一个很好的可视化显示一个节点如何指向另一个节点(或指向 NULL 以结束链)。

它是如何工作的?

如您所述,有趣的部分是声明如何包含对自身的引用。编译器分两步处理:

  1. 它将结构的大小调整为由一个 int 和一个指针组成(无论它们指向什么,它们都是相同的大小)。

  2. 稍后它会键入检查分配并生成适当的程序集。当你写 one->value = 1; 时,它确保 1 是一个整数并生成代码将 1 移动到整数槽。当您写入 one->next = two; 时,它会验证 two 是一个指向节点的指针,并生成代码将该指针移动到结构节点指针的第二个插槽。