Although the array can achieve continuous storage, because the length must be given each time the array is defined, the use is not very flexible, and it is easy to waste resources. The linked list can be dynamically defined, and the malloc() function can be used to apply for the characteristics of dynamic space. Use For this function, the stdlib.h header file needs to be added;
#include <stdio.h>
#include <stdlib.h>
struct linked_list //Declare the structure, which stores the node data, that is, the address of the next node;
{
int date;
struct linked_list *next; //Define a pointer variable to store the next node address
};
int main(void)
{
int i,n,a; //n is the number of nodes
struct linked_list *p,*q,*t,*head; //t is used to traverse the linked list, head points to the first node of the linked list, called the head pointer
p=q=t=head=NULL; // start by pointing them to NULL
scanf("%d",&n);
for(i=0;i<n;++i)
{
scanf("%d",&a);
p=(struct linked_list *)malloc(sizeof(struct linked_list)); //Apply for dynamic space and point to it with p
p->date=a; //You can input data to this node
p->next=NULL; // first point next to NULL
if(head==NULL) //The head pointer points to NULL indicating that it is the first node
head=p; //point the head pointer to the first node
else
q->next=p;
q=p; //Use q to point to the node pointed to by p, because the next time the loop is executed, p needs to
point to the next node
}
//traverse the linked list
t=head; //point t to the first node
while(t->next!=NULL)
{
printf("%d ",t->date);
t=t->next; //t points to the next node
}
return 0;
}