I. Storage of nodes in linked list
The left part of the node in the list is the stored data, and the right part is the address of the subsequent pointer pointing to the next node. C language usually defines a structure type to store a node, as follows:
struct node { int data; struce node *next; //The type of the next node is also struct node, so the type of subsequent pointer must also be struct node.* };
2. Let's connect the nodes.
To string nodes one by one, you need three struct node * pointers: head (header pointer, pointing to the beginning of the list, easy to traverse the entire list from scratch), p (temporary pointer, pointing to those nodes that have not yet been connected), and q (current pointer, pointing to the latest joined node).
Header pointer head is empty when the list has not been established.
struct node *head; head=NULL; //Head pointer is initially empty
Now let's create the first node and point to it with the temporary pointer p.
struct node *p; p=(struct node *)malloc(sizeof(struct node)); //Dynamically apply for a space for a new node and use temporary nodes p Point to this new address scanf("%d",&a); //Read data p->data=a; //Store data in the data domain of the current node p->next=NULL; //Set the successor pointer of the current node to empty, that is, the next node of the current node is empty.
Concatenate the newly added nodes into the list. If the node is the first node created, the head pointer is pointed to the node and the current pointer is pointed to the node; if the node is not the first, the successor pointer of the previous node is pointed to the node and then the current pointer is modified to point to the new node.
if(head==NULL) head=p; else q->next=p; q=p; //Last pointer q Also point to the current node
3. Establishing a linked list and traversing the complete code of the output
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; int main() { struct node *head,*p,*q,*t; int i,n,a; scanf("%d",&n); head=NULL; for(i=0;i<n;i++){ p=(struct node *)malloc(sizeof(struct node)); scanf("%d",&a); p->data=a; p->next=NULL; if(head==NULL) head=p; else q->next=p; q=p; } //Output linked list t=head; while(t!=NULL){ printf("%d ",t->data); t=t->next; } return 0; }
IV. Insertion Node