创建链表而不将节点声明为指针 [英] Creating a linked list without declaring node as a pointer

查看:18
本文介绍了创建链表而不将节点声明为指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在谷歌和一些教科书上搜索了一段时间,但我似乎无法理解为什么在构建链表时,节点需要是指针.

I've been searching around for a good while now on google and a few text books and I can't seem to understand why it is, when building a linked list, that the nodes need to be pointers.

例如.如果我有一个节点定义为:

Eg. If i have a node defined as:

typedef struct Node{
    int value;
    struct Node *next;
} Node;

为什么要创建链表,我会说:

why is it that in order to create a linked list, I would say:

Node *a = malloc(sizeof(Node));
Node *b = malloc(sizeof(Node));
a->value = 1;
b->value = 2;

a->next = b;
b->next = NULL;

而不是:

Node a, b;
a.value = 1;
b.value = 2;

a.next = &b;
b.next = NULL;

据我所知,列表仍然可以正常引用和遍历,唯一的区别是使用点、与号语法而不是箭头?

To my understanding, the list will still be able to be referenced and traversed as normal, the only difference is the use of the dot, ampersand syntax rather than the arrow?

推荐答案

您可以按照您提到的方式创建列表.

You can create the list in a way that you mentioned.

但是你必须关心列表成员的生命周期.如果你的

But you must care for the life time of the list members. If your

节点 a, b;

在函数的范围内,然后在该函数返回后这些将丢失.

are in scope of a function then these are lost after the return of that function.

当您使用指针时,通常会使用堆,并且实例会一直存在,直到它们被删除.

When you use pointers then you usually use the heap and the instances live until they are deleted.

这篇关于创建链表而不将节点声明为指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆