Why do we declare pointer to the same struct in Linked Lists

和自甴很熟 提交于 2021-02-11 17:58:21

问题


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

This is the creation of a linked list. My question is that why do we declared the pointer of the same struct. e.g Node *next. If we are going to have a linked list of integers, can we just use int * next and int *prev instead of using Node *next.


回答1:


Each element in a linked list contains not only the data (int in your case), but also a pointer to the next element (and in a doubly-linked list, like you have, a pointer to the previous element too). Without it, you couldn't construct a list longer than two elements.




回答2:


A structure is use to group list of variables in one common block of memory, this helps in accessing elements using single pointer. In your question you are saying why we not use only int *next if we use that we cannot group other elements, also you cannot save value and link simultaneously.




回答3:


Think of structures as containers which have objects(ints, chars..) stored inside them. To reach an object in a particular container, you need to find the container first, and hence you will need the address of the container(i.e., the address of struct).
Considering the following structure.

struct Node  
{  
int value;  
int *next  
};

You have an integer and a pointer to an integer inside struct Node. When you assign memory for the first structure, it will act like a container holding an integer and a pointer to an integer. In such a case, the chain will end with the first structure itself as you are not pointing to a second structure(from within the first structure), which can hold the pointer pointing to a third structure and so on.
If you want to link this structure to another structure of the same type(in essence creating a linked list), you will need a pointer which can point to another structure of the same type. And hence goes the need to have a pointer to a structure of same kind inside any structure which will be used for a linked list.



来源:https://stackoverflow.com/questions/32026292/why-do-we-declare-pointer-to-the-same-struct-in-linked-lists

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