[Introduction to algorithms] changing the value referred to by the pointer as a formal parameter (Binary sorting tree)

Source: Internet
Author: User
Example 1: assign values to two null pointers.

# Include "stdio. H"

# Include "malloc. H" # Include "string. H" Void testfunction (char ** ptr1, char * & ptr2) // I often like to use * & ptr2 { * Ptr1 = "ABC "; Ptr2 = (char *) malloc (6 ); Strcpy (ptr2, "ABC "); }
Int main () { Char * ptr1 = NULL, * ptr2 = NULL; Testfunction (& ptr1, ptr2 ); Printf ("% s \ n", ptr1 ); Printf ("% s \ n", ptr2 ); Free (ptr2 ); }

Example 2: Implementation of binary sorting tree# Include "stdio. H"# Include "malloc. H"Struct Node{Int data;Node * right;Node * left;};Void insert (node * & root, node * & S) // The passed parameter is the key{If (root = NULL){Root = s;
}Else{If (root-> data <s-> data) // if the data to be inserted is greater than the node, insert the data to the rightInsert (root-> right, S );ElseInsert (root-> left, S );}}
Void creattree (node * & root, int A [], int N){Int I;Node * s;// Root = (node *) malloc (sizeof (node); // do not initialize or apply for space here. Root = NULL;For (I = 0; I <n; I ++){
S = (node *) malloc (sizeof (node ));S-> DATA = A [I];S-> right = NULL;S-> left = NULL;
Insert (root, S );}
}Void output (node * & root){If (root = NULL)Return;Else{Output (root-> left );Printf ("% 5d", root-> data );Output (root-> right );}}Int main (){Int A [] = {, 20 };Node * root;Root = (node *) malloc (sizeof (node); // (size of requested space)Root = NULL; // This sentence must not be less (initialized)Creattree (root, A, 11 );Output (Root );Return 0;}

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.