Creating a linked list without declaring node as a pointer

和自甴很熟 提交于 2020-04-16 02:50:33

问题


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;

rather than:

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?


回答1:


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

Node 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.




回答2:


Your first example will not work. You are declaring two Node pointers. However, since you do not initialize these to anything, it is illegal to deference them, since they don't point to anything. You must first use something like malloc to declare memory for them to point to, or assign them to a previously declared local variable. However, you must also remember to call free when you are done with the memory.

In the second example, you are declaring two Node variables, which you use to store instances of the Node. These will be allocated on the stack if they are local variables, and they will live for as long as they are in scope. They hold valid memory, and thus you can use them in the way you have demonstrated.



来源:https://stackoverflow.com/questions/40331173/creating-a-linked-list-without-declaring-node-as-a-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!