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

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

问题描述

我已经在Google和一些教科书上搜索了好一阵子,但我似乎无法理解为什么在建立链接列表时节点需要是指针.

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天全站免登陆