Be sure to understand the insertion methods and ideas,
I. Head Insertion Method: first fix a head pointer and insert the first node: Insert a node s behind the head, head-> next = S. Insert second node P: Insert before node s, that is, insert p between head and S. The third node is inserted between node P and head. And so on. The new node is always inserted in front of the previous node.
1. As shown in:
2. Step:
3. Code:
Void headcreatlist (list * l) // create a linked list using the header Insertion Method
{
List * s;
L-> next = NULL;
For (INT I = 0; I <10; I ++)
{
S = (struct list *) malloc (sizeof (struct list ));
S-> DATA = I;
S-> next = L-> next; // assign the address pointed to by L to S;
L-> next = s;
}
}
2. Tail insertion: S is the head node. The head Pointer Points to S, and a node D is inserted after S. Then, modify the head pointer and direct the head to D; then insert the node after the new head, and so on. Note: Changes in the header pointer head.
Code:
Void tailcreatlist (list * l) // create a linked list by means of tail insertion
{
List * s, * R;
R = L;
For (INT I = 0; I <10; I ++)
{
S = (struct list *) malloc (sizeof (struct list ));
S-> DATA = I;
R-> next = s;
R = s;
}
R-> next = NULL;
}
Iii. Summary:
The following figure shows how to insert three nodes into a linked list: