LNode is a node variable, LinkList is a node pointer variable, which is equivalent to LNode*

typedef struct LNode{		// Define single linked list node types
	int data;
	struct LNode *next; 
}LNode,*LinkList;
Copy the code

Example 1: Wrong way to initialize a singly linked list of leading nodes

void InitList(LinkList L)
{	
	L = (LinkList)malloc(sizeof(LNode));
	L->data = 3;
    L->next = NULL;
}

void Empty(LinkList L)
{
	if(NULL == L)
	{
		printf("Linked list does not exist \n"); 
	}
	else if(NULL == L->next)
	{
		printf("Empty table \ n"); }}int main(a)
{
 	LNode p;
 	p.data = 2;
 	printf("p.data = %d\n",p.data);
 	
 	LinkList L = NULL;
	InitList(L);
	printf("L->data = %d\n",L->data);
    return 0;
}
Copy the code

The output

p.data = 2The linked list does not existCopy the code

The correct way: initialize a singly linked list of leading nodes

void InitList(LinkList *L)
{	
	(*L) = (LinkList)malloc(sizeof(LNode));
	(*L)->data = 3;
	(*L)->next = NULL;
}

void Empty(LinkList L)
{
	if(NULL == L)
	{
		printf("Linked list does not exist \n"); 
	}
	else if(NULL == L->next)
	{
		printf("Empty table \ n"); }}int main(a)
{
 	LNode p;
 	p.data = 2;
 	printf("p.data = %d\n",p.data);
 	
 	LinkList L = NULL;
	InitList(&L);
	printf("L->data = %d\n",L->data);
    return 0; 
}
Copy the code

The output

p.data = 2Empty table L - > data =3
Copy the code

Why can’t the first InitList(LinkList L) function initialize singly linked list L? Isn’t that the address you’re using?

A:

L = (LinkList)malloc(sizeof(LNode));

Here Lis the parameter to InitList, which is a local variable that will not exist after the function finishes running.

The L pointer variable in main is actually stored in a global variable. The two L’s are not the same L.

In example 1, LinkList Lin main initially points to NULL

InitList(L) is executed from the start. Although Lis also operated on in InitList, Lis the parameter L in InitList, and all subsequent operations are performed on parameters, as shown in the following figure

In example 1, we pass in the LinkList variable L, which is a first-level pointer. We cannot change the value of argument L to point to the newly allocated LNode, so the argument L still points to NULL, because the output result “the linked list does not exist”.

(*L) = (LinkList)malloc(sizeof(LNode)); (*L) = (LinkList)malloc(sizeof(LNode));