简体   繁体   English

创建链接列表时是否不需要创建实际节点?

[英]Do we not need to create actual nodes while creating a linked list?

I'm studying linked lists from this article. 我正在研究本文的链接列表

The writer of the tutorial never creates actual nodes, but only pointer variables of type node, as you can see with the following code... 本教程的作者从不创建实际节点,而仅创建节点类型的指针变量,如下面的代码所示。

struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;

and then he allocates space for them in the heap... 然后他在堆中为他们分配空间...

head = (struct node*)malloc(sizeof(struct node)); 
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));

why doesn't he ever create actual nodes? 他为什么不创建实际的节点? code for which should look something like this... 代码应该看起来像这样...

struct node head;
struct node second;
struct node third;

If my knowledge is right (correct me if I'm wrong). 如果我的知识是正确的(如果我错了,请纠正我)。 Simply declaring the pointer variable doesn't create the actual variable(node in case of linked lists), and hence cannot be dereferenced like the writer of the tutorial in the article using the code 简单地声明指针变量并不会创建实际变量(在链表的情况下为节点),因此不能像本文中使用代码的教程作者一样被取消引用。

head->data = 1;

I mean, if that works, then why doesn't this work? 我的意思是,如果这行得通,那为什么不行呢?

int *a;
a=5;
printf("%d",*a);

Obviously, the above code doesn't output 5. 显然,以上代码不会输出5。

Which means that another variable needs to be created, and then it needs to be stated that the address of the variable is stored in a pointer variable, only then it can be dereferenced...like the following code... 这意味着需要创建另一个变量,然后需要声明该变量的地址存储在指针变量中,然后才可以取消引用它,就像下面的代码一样……

int *a;
int b=5;
a=&b;
printf("%d",*a);

This outputs 5. 输出5。

So how does the author gets away with not creating the nodes? 那么作者如何摆脱不创建节点的困扰呢? He simply creates the pointer variables and then simply dereferences them.... 他只是创建指针变量,然后简单地取消引用它们。

The nodes are in the heap, that's what malloc is for. 节点在堆中,这就是malloc目的。

To use code without linked list to explain, it's similar to: 要使用不带链表的代码进行解释,它类似于:

int *a = NULL;
a = malloc(sizeof(int));
*a = 5;
printf("%d",*a);

The structure pointers are created so that they can refer to address.Since normal structure variables can't store the address, this syntax is wrong. 创建结构指针以便它们可以引用地址。由于普通结构变量无法存储地址,因此此语法是错误的。 struct node head; struct node second; struct node third;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM