[英]what is the purpose of adding “struct name *next” inside “struct name” in linked list. I mean i actually cant process what exactly happens
#include<stdio.h>
#include<stdlib.h>
typedef struct employ
{
int reg;
int sal;
char *name;
struct employ *next; // I want to know the purpose of this line
}EMP;
int main(void)
{
EMP *first,*emp1,*emp2,*emp3,*ans;
first = (EMP *)malloc(sizeof(EMP));
first->next = NULL;
/////first///////
emp1 = (EMP *)malloc(sizeof(EMP));
if(emp1 == NULL)
{
perror("malloc error");
exit(1);
}
emp1->reg = 100;
emp1->sal = 30000;
emp1->name = "james";
emp1->next = first;
first = emp1;
/* I havent completed the program bcoz its not necessary here */
In a linked list, each node contains a pointer to the next node. 在链接列表中,每个节点都包含一个指向下一个节点的指针。
struct employ *next;
is used to achieve that effect 用于达到那种效果
+---------+ +---------+
| Node1 |------->| Node2 |----> ...
+---------+ +---------+
if you are in node1, next is a pointer to node2, that way you can accesss next element from the current element 如果您在node1中,则next是指向node2的指针,这样您就可以访问当前元素中的下一个元素
A linked list is a data structure consisting of a group of nodes which together represent a sequence. 链表是一种由一组节点组成的数据结构,这些节点一起代表一个序列。 Here the
reg
, sal
and *name
represent your data structure and *next
will hold the link to next element in the list. 这里
reg
, sal
和*name
代表您的数据结构, *next
将保留指向列表中下一个元素的链接。
Consider the following data structure 考虑以下数据结构
struct sample {
int number;
struct sample *next;
};
The pictorial representation for this structure would be 该结构的图形表示为
The above example has 3 elements, every element is an individual structure variable. 上面的示例包含3个元素,每个元素都是一个单独的结构变量。 In the above example the variable 1 has members
number
and *next
. 在上面的示例中,变量1具有成员
number
和*next
。 Here, the number
contains 12
and the *next
contains the address of the structure variable holding the data 99
. 此处,
number
包含12
, *next
包含保存数据99
的结构变量的地址。 Since the type of the variable holding the data 99
is of type struct sample
that is why we take *next
type as struct sample
type. 由于变量保存数据的类型
99
是类型struct sample
,这就是为什么我们把*next
类型struct sample
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.