Insert a single linked list. I think it should be the most basic thing. Today we will introduce a concise version.
Requirement: Insert a node to the correct position of the linked list. The values of the nodes in the current linked list are arranged in ascending order.
Traditional insert operations:
Int insertnode (node ** rootp, int new_value) {node * Current; node * Previous; node * New; current = * rootp; previous = NULL; while (current! = NULL & Current-> value <new_value) {previous = current; current = Current-> link;} new = (node *) malloc (sizeof (node )); if (New = NULL) return 0; New-> value = new_value; New-> link = current; If (previous = NULL) {* rootp = new ;} else {previous-> link = new;} return 1 ;}
The aboveAlgorithmAlthough there is no problem, you need to define the current and previus2 variables,
In addition, special processing is required for inserting data into the first node.
For the improved version, you only need to define a current variable and do not need to insert it to the first node for special processing.
Int insertnode (node ** linkp, int new_value) {node * Current; node * New; while (current = * linkp )! = NULL & Current-> value <new_value) {linkp = & T-> link;} new = (node *) malloc (sizeof (node )); if (New = NULL) return 0; New-> value = new_value; New-> link = current; * linkp = new; return 1 ;}
If the initial status of the linked list is as follows:
It can be seen that the new node needs to be inserted into a header.
The status of each pointer before insertion is as follows:
Insert new node