C and pointer notes-simple insert operations for single linked lists

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.