MindMap Gallery C language and data structures
The basic knowledge related to C language and data structure has been organized, and the grammar has been supplemented and explained with examples to facilitate understanding. It can be used as a reference book for finding grammar, and can also be used to learn and understand these two parts.
Edited at 2023-08-16 21:39:05Avatar 3 centers on the Sully family, showcasing the internal rift caused by the sacrifice of their eldest son, and their alliance with other tribes on Pandora against the external conflict of the Ashbringers, who adhere to the philosophy of fire and are allied with humans. It explores the grand themes of family, faith, and survival.
This article discusses the Easter eggs and homages in Zootopia 2 that you may have discovered. The main content includes: character and archetype Easter eggs, cinematic universe crossover Easter eggs, animal ecology and behavior references, symbol and metaphor Easter eggs, social satire and brand allusions, and emotional storylines and sequel foreshadowing.
[Zootopia Character Relationship Chart] The idealistic rabbit police officer Judy and the cynical fox conman Nick form a charmingly contrasting duo, rising from street hustlers to become Zootopia police officers!
Avatar 3 centers on the Sully family, showcasing the internal rift caused by the sacrifice of their eldest son, and their alliance with other tribes on Pandora against the external conflict of the Ashbringers, who adhere to the philosophy of fire and are allied with humans. It explores the grand themes of family, faith, and survival.
This article discusses the Easter eggs and homages in Zootopia 2 that you may have discovered. The main content includes: character and archetype Easter eggs, cinematic universe crossover Easter eggs, animal ecology and behavior references, symbol and metaphor Easter eggs, social satire and brand allusions, and emotional storylines and sequel foreshadowing.
[Zootopia Character Relationship Chart] The idealistic rabbit police officer Judy and the cynical fox conman Nick form a charmingly contrasting duo, rising from street hustlers to become Zootopia police officers!
C language and data structures
C language fragmentation
Common escape characters
picture
system("cls") and system("pause") [clear screen function and pause function]
Operator order
pointer
Pointer related concepts
Pointer variable: The C language stipulates that only a special [variable] can be used to store the address (the number of bytes in memory). This type is called a pointer type.
Pointer: For a memory unit, the address of the memory unit is the pointer.
Note: Since the required variable can be found through the address, the C language vividly calls the address a pointer.
Personal description of pointer variables: Pointer variables are a special kind of variables, which can [only] store the [address] of [variables of the same type] or store 0. The value of the variable can be [indirectly accessed] through the address, and [accessed memory] The address is for more convenient operation of the address in the memory unit]
Usage: Assign the first address of the variable and the first address of other data structures to [pointer variable]
Definition and initialization of pointer variables
The definition of pointer variable: should include [data type name] and [pointer variable name]
Format: data type name * pointer variable name 1, * pointer variable name 2 or define one separately and then define it multiple times to complete.
Note: The data stored in pointer variables must be the [address] of [variables of the same type]. This is also the reason why a data type name is required when defining [it can indicate whether the pointer and variable data types are the same]. If we define If the type of the variable is the same as the pointer type, then the first address of the variable storing data can be assigned to the pointer.
Initialization of pointer variables: Define first and then initialize or initialize while defining. Otherwise, it is wrong.
Format: data type name * pointer variable name = initial value;
Note: The initial value is the address, so if you assign the variable address to a pointer variable, you need to use the address operator.
Summary: During definition and initialization, the book states many issues that need attention, but these issues all revolve around definitions and concepts. As long as you keep in mind [the narrative summarized by yourself], these issues can be solved through concepts.
pointer variable reference
Method: In C language, the reference to pointer variables can be completed through [* value operator] and [& address operator]. The former can take out the variable in the address, and the latter can take out the variable. address.
Note: You need to pay attention to the priority, order of operations, and understand the special *address operation when defining [it does not serve as a value when defined]
Key point: In the application of two-dimensional and multi-dimensional arrays, there will be some particularities, which can be learned in [Representation of pointers and multi-dimensional arrays].
Summary: After a pointer variable is correctly defined and initialized, if the pointer variable is p, then "p" when used at this time is a variable that stores the address (such as printing the value of p and displaying it as an address), and by taking the value The [*] operator can obtain the value of [the address points to the variable]
Note: After the definition of the pointer variable is completed, if the operation does not involve the data pointed to the variable but only the address in the pointer variable, please do not add the * sign, and vice versa. (Please contact the [Pointer Operations] section for details.
Example:
Pointer arithmetic [Speciality]
Method: The operations of pointer variables are generally divided into addition and subtraction. Pointers can add or subtract integers, but this operation of pointers is different from the usual operations.
Summary: Due to the relationship between memory units and pointers, this operation is not just the addition and subtraction of addresses, but the "addition and subtraction of the product" of [number] and [byte size of the corresponding data type]. At the same time, due to the address of the variable The essence is the starting address of the memory unit. Therefore, through pointer operations, the address addition and subtraction results generated are determined by the byte size of the corresponding data type, rather than the direct address value plus or minus an integer.
Example: [It can be seen that the value of the variable in the pointer has changed by 16, which is the product of the subtracted 4 and the basic integer number of bytes 4]
pointers and arrays
Notice
The connection between pointers and arrays: The array name is neither a pointer constant nor a constant pointer. At some point, it can degenerate into a pointer pointing to the first element of the array. That is to say, the array name can be implicitly converted to a pointer type. .
For example: When passing an array name to a function that accepts pointer type parameters, the array name will be converted into the corresponding pointer type.
Advantages: Since array subscripts need to be converted into pointers during compilation, directly using pointers can reduce system compilation time.
Note: You need to consider whether the array is out of bounds when using it, and you also need to consider it when using pointers.
Reference to array element
Subscript method: expressed by array subscript, please find the details in the array section.
Pointer method: All elements of the array are represented by the operation of pointers. It is necessary to pay attention to the specialness of pointer operation, which has been summarized in pointer operation.
Supplement: It can be seen that for basic integer types, each variable occupies 4 bytes. When using pointer operations to point to array variables, you can directly add or subtract integers without adding the number of bytes.
Key point: The subscript method and the pointer method are closely related in subsequent studies, especially in the connection between pointers and multi-dimensional arrays. The representation of pointer method has detailed examples in [Representation of pointers and multi-dimensional arrays]
Representation of pointers and multidimensional arrays
Properties of multidimensional arrays: In all arrays, we use subscripts to represent arrays. For arrays of different dimensions, we will represent the corresponding subscript. When the subscript is less than the dimension, it represents the address of this dimension instead of this dimension. The value of the number. In multi-dimensional array pointer operation, when the array name is added or subtracted, it indicates the first address of the added value, and the value operator needs to be used twice.
Example:
Pointers and one-dimensional arrays
Format: pointer variable name = array name
Summary: One-dimensional arrays and pointers are closely related. The array name is assigned to the defined pointer variable, so that the array elements are represented through pointer operations.
Pointers and two-dimensional arrays
Summary: There are two ways to represent two-dimensional arrays. The first way is to use the first half of the subscript as an address, and use address operations to represent other elements in the array. Only by completing the following subscripts can specific array elements be represented. . The second type is represented by the array name and the value operator. When * is used for the first time, it still represents the address. When it is not used, it still represents the address. Only when * is used twice at the same time can it represent the address pointed to. variable.
Note: In the above explanation, the use of array names plus pointers to represent array elements is completely different from the use of pointer variables to represent array elements. Wrong use will lead to program errors. [There are special pointer variables later to represent arrays]
Pointer variable pointing to a two-dimensional array
Reason: For a two-dimensional array, the array name cannot be directly assigned to the defined pointer variable like a one-dimensional array. Therefore, a pointer variable specifically pointing to a two-dimensional array was born.
Definition form: data type name (*pointer variable name)[number of elements]
Formal explanation: [Number of elements] indicates that the target variable is a one-dimensional array, and specifies the number of elements in the one-dimensional array. The parentheses are because the priority of the operation must be strictly specified, otherwise it will lead to the definition of a pointer variable that does not point to a two-dimensional array.
Features: After this variable is assigned a value, it is equivalent to representing the array elements in a two-dimensional array through the array name and value operator. [The number of elements that follows represents the number of array columns]. It is equivalent to assigning the array with the first half of the subscript, that is, the address of the first element of each dimension of the array, to this variable. [The last sentence is explained in detail in the Pointers and Two-Dimensional Arrays section]
Explanation of [number of elements]: The number represents the number of columns equivalent to the array
array of pointers
Note: Array elements are all pointer type elements, that is to say, each element in the pointer array will store a pointer variable.
Declaration format
General declaration format: <storage type><data type>*<array name>[<array length>];
Complete declaration format: <storage type><data type>*<array name>[<array length>]={initial value list};
Note: Definition and assignment should be separable and will not be expanded upon in detail here.
Important: The elements in an array of pointers are both array elements and pointers. Therefore, when referencing them, pay attention to both their array element characteristics and their pointer characteristics. [You can use subscripts to reference array elements, or you can use array names to reference the addresses of corresponding locations. If the array element itself is a pointer, be careful to use the value operator to access the variable pointed by the pointer]
Comparison of character pointer array and two-dimensional array
The difference: the latter occupies continuous memory space when stored. The former is a scattered memory space.
Characteristics of two-dimensional character arrays: When a two-dimensional array represents a string, it needs to occupy a continuous storage space, but much of the storage space in the middle may be blank. Therefore, when defining, you need to specify the number of columns as the longest string plus one.
Pointers and strings
pointer to string
Advantages: When an address is assigned to a pointer, the pointer's pointer changes accordingly. Therefore, when we use character pointer variables, it will be more convenient to process strings.
Reference method: Define a character pointer and use it to point to the starting address of the string to reference the string. At this time, there is no need to use the address operator.
define format
char *pointer variable name;
char *pointer variable name = string constant;
Note: You can define it first and then initialize it, or you can do it at the same time.
Output method: Output the string through %s and character pointer variable name. If you want to output a specific character in a string, you can use pointer arithmetic to change the address pointed by the character pointer to the address of the specific character.
The difference between character pointers and character arrays
First: the character pointer variable name can be assigned multiple times, but the character array name is an address constant and cannot be assigned. Secondly, the size of the array is fixed and space needs to be allocated in advance.
Second: The type and occupied storage unit are different. The former is the first address of the string, and the latter is the allocated space.
Third: The elements in the array can be reassigned, but we cannot indirectly modify the value of the character constant through the character pointer, otherwise the consequences are unpredictable.
Summary: The character pointer is a variable that can be directly assigned multiple times and points to the first address of the string. The size of the character array is fixed, and the elements in the array are assigned multiple times. When assigning values directly, they must be assigned during initialization. You can also use input functions for assignment, but you cannot use assignment statements.
pointers and functions
Pass pointer variable as function parameter
Purpose: Use pointers as function parameters to ensure that the address passed to the formal parameter is the address. Since modifications made by the called function to parameters are not passed to the main function, sometimes pointer variables are used as function parameters to save such modifications.
Features are: shared memory, two-way transfer
Explanation of this method: To implement this method, you need to ensure that the formal parameters passed are pointers, and secondly, use the formal parameters to participate in the function. You need to know that when executing a statement in a function, it is not the address of the formal parameter that participates in the function, but the formal parameter. Due to the particularity of the pointer, the transformation of the formal parameter at this time is actually the transformation of the variable in the memory address. To ensure accuracy, I verified it and gave an example below
examples:
Pointer to function (function pointer)
Reason: Function names and array names have similar characteristics. The function name represents the starting address of the function. The compiler uses the function name to index the entry address of the function.
Definition of function pointer
Definition: In order to operate functions with the same type attributes, the C language introduces the function pointer. If the first address of the function is assigned to the pointer variable, then the variable points to the function. We can find and call the corresponding function through the pointer variable.
Definition form: data type name (*function pointer name)();
Explanation: The data type defines the return value type of the function, (*function pointer name) determines the pointer variable pointing to the function, () indicates that the pointed object is a function.
Initialization and use of function pointers
Function pointers have no independent function code and must be initialized. There are two forms of initialization, one is to assign the function name directly, and the other is to assign the function name through the address operator. Of course, you can also initialize it at the same time as defining it, and then adopt two initialization methods.
Initialization method
Function pointer name = function name or function pointer name = & function name
Data type name (*function pointer name)( )=function name
The general form of calling a function using a function pointer variable
(*Function pointer name)(actual parameter list);
Function that returns a pointer value
The function type is determined by the return value. This function whose return value is a pointer is called a pointer function.
Definition form: data type * function name (parameter list);
Note: The return value must be a variable pointer and array pointer of external or static storage class.
pointer to pointer
Definition: If a pointer variable stores the address of another pointer variable, the pointer variable is called a pointer variable pointing to a pointer.
Definition form: data type name **p
Explanation: The number of * signs determines the level of pointer variables. Only pointer variables of the same type and level can assign values to each other. At the same time, the high-order pointer must be assigned by the adjacent low-price pointer.
Understanding: For a given variable, assign it to pointer variables of different levels level by level. They all point to the original variable. The usage is similar to the first-level pointer variable.
examples:
Pointers and dynamic memory allocation
Because the prototype of the dynamic memory management function is defined in the standard header file <stdlib.h>, it needs to be added when using it.
malloc function
Function: malloc allocates a continuous space of length size from the dynamic storage area of the memory. The parameter of the malloc function is an unsigned integer, and the return value is a pointer to point to the starting address of the allocated dynamic storage area. It should be noted that when the space is failed to be allocated successfully, the malloc function will allocate a null pointer, so when we use it, we must detect whether the return value is a null pointer and perform corresponding operations. For example, in the figure below, the operation that needs to be performed can be to display allocation errors.
Prototype: void *malloc(unsigned int size)
Explanation: void * is the type of the return value, unsigned int is written as an unsigned integer, and size is used to calculate the size, such as size(int), the result is 4.
examples:
calloc function
Key point: The difference from the malloc function is that the calloc function will initialize the allocated memory space to zero first, and the others are basically the same.
Prototype: void *calloc(num, size)
Explanation: The usage is the same as the malloc function. When one or more of num and size are zero, an allocation error will occur, so you know.
Usage and examples:
free function
Reason: Since memory cannot be allocated infinitely, we must save resources. Therefore, after using the dynamic memory management function, the allocated space must be released to facilitate the use of other variables.
Prototype: void free (void *ptr)
Precautions
Undefined behavior occurs if free does not point to previously allocated space.
free releases the allocated space, but does not change the original value of ptr. That is to say, ptr still points to the original address, but the address is no longer valid.
If ptr is a null pointer, this function does nothing
After free, ptr must be set empty, ptr=NULL, otherwise, there will be an error when the variable ptr is accessed again.
free cannot be released repeatedly, otherwise there will be errors
Usage and examples
free: Under the premise of ensuring correctness, the non-null pointer returned by malloc and calloc allocation will only be released once. After release, it must be made empty and the pointing of the original pointer will not be changed.
The above three functions are for reference only, so any deficiencies can be searched online.
Example of how malloc function and free function work together
pointer to structure variable
Explanation: After the structure variable is declared, storage space will be allocated in the memory, and the starting address of this space is the address (pointer) of the structure variable. Therefore, we can access through pointers by assigning values to pointers. At this time, pay attention to the definition of pointer variables, "can only store [same type]", so when faced with our custom structure, it cannot be assigned directly . We need to first define a pointer of the same type through this structure, and then assign the address of the structure variable to the pointer.
General form: struct structure name * pointer variable name or (name after typedef) * pointer variable name
Explanation: The essence is the definition of pointers, so it is consistent with the use of basic type definitions. Therefore, the name after typedef also has the same effect.
Note: When assigning a value, please find the address of the structure variable. The assignment process belongs to the initialization of the pointer variable, so don't bother.
Key point: You can use pointer operations to point to the first address of the structure array, and then indirectly access the variables in the array. For example, array a - a[1]=*(a 1), a[1][1]=*(*(a 1) 1). [If you use a pointer variable, the method is the same as the array name method, and you only need to simply replace it]
Discovery: You can directly use the structure name to define variables pointing to the structure in the structure. 【Doubtful】
Form: structure name * pointer variable name; [without struct at this time]
Comprehensive diagram of pointers, arrays, functions, and structures
Pointer constant [variant of pointer type, used to limit modification of the address pointed to]
Definition: The essence is a constant, and it is modified with a pointer. The value of a pointer constant is a pointer. Because this value is a constant, it cannot be assigned.
Code form: int* const p;
Effect: It is a constant. The pointer can only point to the specified address and cannot be changed, but the value in the address can be changed [similar to the array name, but different]
Constant pointer [variant of pointer type, used to limit modification of the value pointed to]
Definition: Also called a constant pointer, it can be understood as a constant pointer, that is, this is a pointer, but it points to a constant. This constant is the value (address) of the pointer, not the value pointed to by the address.
Code form: int const* p; const int* p;
Effect: Addresses including variables can be accepted and can be pointed to an address arbitrarily. However, the variable value cannot be changed by modifying the pointer. It can be changed by the original method of the variable.
Commonly used input and output functions
About the concept of input and output functions
The so-called input and output is mainly based on the computer host and is completed through input devices and output devices.
The C language itself does not have input and output function statements, but it provides a wealth of input and output function library functions. The standard input and output standard library functions are defined in the header file stdio.h (English abbreviation, no further details). When using these library functions, you need to use the macro command #include to include the header file into the source file.
How to use #include
#include <stdio.h>
Explanation: Find the specified file in the include directory.
#include "stdio.h"
Explanation: First search in the directory where the source file is located, and then search in the standard way.
Character input and output
Character input function
Limitation: Can only be applied to input of [single character]
How to use the three: Assign the input characters to character variables or integer variables, which can serve as assignment statements or participate in operations as part of the operation.
Understanding: The character input functions are defined in stdio.h and have no parameters.
getchar (can be used to clear the buffer, that is, act as a pause key)
Limitation: Only the first character is received. If a number is entered, it will be processed as a character. You must press Enter for successful entry and will be displayed on the screen.
Format: getchar(); or variable name=getchar();
getche
Explanation: Basically similar to getchar, the difference is that it will be echoed on the screen without a carriage return
getch
Explanation: Basically similar, the difference with getche is that it will not be echoed on the screen.
examples
character output function
putchar
Usage format: putchar (formal parameter);
Explanation: Output a single character to the screen, where the formal parameters can be character constants, character variables and expressions. If the formal parameter is a control character, the control function is executed. Because the control character is invisible, the cursor position changes and sounds can only be visually observed.
String processing function [defined in the <string.h> header file]
String output function puts
Format: puts (character array name/string)
Function: Output a string to the computer screen and wrap the string after the output is completed.
Note: The character array must end with '\0'.
String input function gets
Format: gets (character array)
Function: Enter a string ending with a carriage return from the keyboard and put it into the character array, and then automatically add '\0' at the end to get a function value, which is the starting address of the character array.
Description: The input string should be smaller than the length of the character array.
String concatenation function strcat
Format: strcat (character array 1, character array 2)
Function: Connect the string in character array 2 to character array 1, remove the '\0' at the end of the string in character array 1, and retain the '\0' at the end of string 2.
Note: Character array 1 must be large enough. The return value of this function is the first address of character array 1.
String copy function strcpy
Format: strcpy (character array 1, character array 2)
Function: Assign the string in character array 2 to character array 1, including the trailing '\0'. Character array 2 can also be a string constant, which is equivalent to assigning a string to a character array.
Note: Character array 1 must be large enough, and assignment statements cannot be used to assign values to the character array.
String comparison function strcmp
Format: strcmp (character array 1, character array 2)
Function: Compare two strings from left to right [the character ASCLL is compared] until they encounter differences or '\0'.
The former is equal to the latter, and the return value is 0
The former is greater than the latter, and the return value is a positive integer
If the former is less than the latter, the return value is a negative integer
Note: When comparing strings, only strcmp can be used. It can be used between string constants, and even between character arrays and string constants.
String length measurement function strlen
Format: strlen (character array)
Function: Measure the actual length of the string [excluding '\0'] and use it as the return value.
Other string processing functions
Format: strupr (character array), function: convert all characters to uppercase
Format: strlwr (character array), function: convert all characters to lowercase
Format: strset (character array, character), function: convert all characters into specific characters
Format control input and output functions
Format control output function
Definition: The printf function is called the format control output function
Definition location: <stdio.h>
Basic format: printf("format control string", parameter 1, parameter 2,...);
Extension: The format control string includes two parts, one part is a normal character sequence or an escape character sequence. The other part is the format declaration string. The former is printed as it is, and the latter is effective according to the function.
Parameters: can be constants and variables, expressions or function calls
The two must be in one-to-one correspondence. If there is an error, the wrong value will be output or cannot be output [because the compiler only checks the calling form and does not analyze the format control string]. At the same time, when outputting data, all data types are given priority according to the format character control string.
Declaration of printf function format
Full format: %[flag][output minimum width].[precision][length] type
%: It is the starting symbol and is essential
Flags: Fillable options, -, 0, #, space [mainly auxiliary for output]
Minimum output width: This refers to the field width, which is the number of characters displayed. If it is less than it, it defaults to right alignment and left padding. If it is larger than it, output it as is.
Precision: The number of valid decimal places displayed, any excess will be rounded off.
Length: ll or h, l is long for integer type, double for real type, h is used to modify integer type to short type
Type: Specify the type of output data. [It is recommended to keep the common ones in mind]
The evaluation order of printf: The order is different in different compilation systems. In VC, it is from right to left [very important, be clear]
Format control input function
Definition: The scanf function is called the format control output function
Definition location: <stdio.h>
Basic format: scanf("format control string", address 1, address 2,...);
Extension: The format control string includes one or more format control characters starting with %, and % is followed by one or more format control characters, which are used to occupy places so that they can correspond to the subsequent addresses. Use the format control characters at the corresponding positions. Determine the data input format
Scanf function declaration
Full format declaration: %[*][input width][length] type
%: The starting character of the format declaration, indispensable.
[*]: Read but do not assign, skip it when assigning
Input width: the number of valid characters entered
Length: l or h. When it is an integer, the former is a long integer and the latter is a short integer. When it is a real type, it is a double type.
Type: similar to printf
A description of the scanf function
The format is very important, please be sure to use it in the complete format, otherwise an error will occur
The format control characters and addresses must correspond, otherwise the program will be unrecognizable. If there are characters between format control characters, characters must also be added between addresses.
Data type (a collection of values and the collective name of all operations defined on this collection)
Reason: In mathematics, data is not classified. However, in computers, since the storage space is limited by physical hardware, it is impossible for the storage space to store infinitely large or infinite digits of decimals. Therefore, it is necessary to classify the data.
basic type
integer
Knowledge related to integer data
Definition: variable defined by int
Representation method: In C language, it can be expressed in decimal, octal, and hexadecimal.
Storage method: In the computer, it is stored in binary format. Positive numbers are stored in original code, and negative numbers are stored in complement format.
Classification
scope
short
Occupied bytes: 2 bytes
[Signed] Representation range: -2 to the 15th power ~ 2 to the 15th power -1
[Unsigned] Representation range: 0~2 to the 16th power
Basic integer type (int)
Occupied bytes: 4 bytes
[Signed] Representation range: -2 to the 31st power ~ 2 to the 31st power -1
[Unsigned] Representation range: 0~2 to the 32nd power
long
Occupied bytes: 4 bytes
[Signed] Representation range: -2 to the 31st power ~ 2 to the 31st power -1
[Unsigned] Representation range: 0~2 to the 32nd power
long long
Occupied bytes: 8 bytes
[Signed] Representation range: -2 to the 63rd power to 2 to the 63rd power -1
[Unsigned] Representation range: 0~2 raised to the 64th power
symbol
Signed integer (signed int): The highest bit of the storage unit is the sign bit, 0 is positive, 1 is negative, and the others are numerical bits.
Unsigned int (unsigned int): All binary bits are used to store values without a sign bit.
The difference between the two: first is the difference between positive and negative, and secondly, the two defined variables have different ranges of numbers that can be represented, which will be explained in detail in the range of basic integer types.
real type
Knowledge about real data (floating point data)
Representation method (real constant): In computers, real constants can be expressed in decimal and exponential forms.
Storage method: In computers, real data is stored in exponential form, and real data is divided into decimal part and exponential part. C language does not specify how many digits are decimal places and how many digits are exponents. This is determined by the compilation system. Generally speaking, most compilation systems use 24 decimal places and 8 exponents. The former represents precision and the latter represents range.
Requirements for using exponential form
1. The format is aEn, for example, 123, which means 1.23E2
2. The letter E or e must be preceded by a number and followed by an integer.
3. Standardization (not mandatory), that is, there is and is only one non-0 number to the left of the decimal point before e, and the following must be an integer.
Accuracy of real data
Reason: Limited by physical hardware, computer memory is not infinite, so it cannot save infinite decimal places. Therefore, the real data in the computer are approximate values. [This is also the case. When comparing real data, it is generally whether it is close, not whether it is equal]
Precautions
When using real data, you need to select single-precision real or double-precision real according to your needs.
Do not use real type data to represent [larger integers], because the [storage form] of real type data in the computer causes that if it exceeds the range of the real type, the data will lose some digits, so that the value will change. .
Try to avoid subtracting a too small number from a large number, as this may cause the decimal to be lost.
Computer processing of real-type constants: The computer will process real-type constants as double-precision real-type data. The disadvantage is that it reduces operations. Add the letter f or F after a real constant, and the computer will treat it as single-precision real data. Adding l or L will treat it as long double-precision real data.
Classification
Accuracy
Single precision real variable (float)
Occupied bytes: 4 bytes
Effective digits: 6
Range: -3.4e to the 38th power ~ 3.4e to the 38th power
Double precision real variable (double)
Occupied bytes: 8 bytes
Effective digits: 15
Range: -1.7e to the power of 308~1.7e to the power of 308
long double
Occupied bytes: 8 bytes or 16 bytes
Effective digits: 15 or 19
Range: -1.7e to the power of 308~1.7e to the power of 308 or -3.4e to the power of 4932~3.4e to the power of 4932 [caused by differences in compilers]
Character data
character variable
Character variables are defined using the keyword char, and an initial value is assigned when they are defined.
Format: char variable name;
Character constant
Explanation: There are two forms of character constants, one is ordinary character constants, and the other is escaped character constants
Ordinary character constants: Use [' 'single quotes] to enclose a [single] [character] and store the corresponding encoding (ASCII) in the memory. It can be processed as either a character or a number.
Escaped character constant: a character sequence starting with [backslash\]. [It is recommended to understand commonly used escape characters]
Operations on character data
When putting characters into a character variable, the character variable stores the corresponding ASCII code. It can be used as both character processing and data processing (ASCII is involved in the operation at this time), so it can be used as an integer variable. to handle. At the same time, two forms of data can be output through output statements.
String constant
Definition: [Character sequence] enclosed by [double quotation marks] and ending with [\0] (specified by C language)
String constants cannot be assigned to character variables
There are no character variables, but character arrays and character pointers can be used
The \0 at the end also takes up one byte of space, just two double quotes, also called a string constant, also called an empty string, with a size of one byte.
Note: Character data only occupies one byte in memory.
abstract data type
It can be represented and implemented through inherent data types, which is somewhat similar to the structure in C language
Algorithms (definitions only) and program control structures
algorithm
Reason: Computer is always a tool to solve practical problems. It is inevitable to encounter specific problems and the steps and methods generated by algorithms to solve these problems.
Definition: It is a well-defined and ordered set of instructions.
Problem size: It is not the size of the input data, but the essence of the problem size.
Characteristics of algorithms
Finiteness: The algorithm must be able to complete the algorithm through finite steps within the range of human tolerance in every situation it contains.
Feasibility: The algorithm can be completed through the identified basic operations and limited steps.
Determinism: Each statement must be certain and cannot be ambiguous, ensuring that the program produces the same result under the same input conditions.
I/O: The algorithm must have zero or more inputs, and one or more outputs.
Validity: Each step of the algorithm must be able to be executed efficiently
In addition, the determination of the quality of an algorithm also needs to consider correctness, readability, robustness, time complexity and space complexity (efficiency).
Algorithm representation
Natural language: a language that people use daily, but people’s understanding of it is prone to differences, which reduces the certainty of the program.
Flow chart: The regulations are relatively clear, but too many flow lines can easily cause confusion, make modifications inconvenient, and take time and effort to draw.
N-S diagram: A truly structured method, but it still has factors that make it complicated to modify and draw.
Pseudocode: has many advantages, is easy to modify, uses computer language and natural language, and is easy to understand.
General steps used: Top-down. Solving problems does not require dealing with details all at once. You must be able to divide big problems into small ones.
Algorithm execution time
Explanation: The execution time of the algorithm is equal to the sum of the execution time of all statements, and the execution time of all statements is equal to the time of execution once and the number of executions.
Statement frequency: The number of times a statement is repeated.
(Asymptotic) time complexity
Definition: The order of magnitude of algorithm execution time is called time complexity, T(n)=Q(f(x))
Sorting (time complexity): constant order < logarithmic order < linear order < linear logarithmic order < square order < cubic order < kth power order < exponential order
Note: It increases with the size of the problem.
(Asymptotic) space complexity
Including: [Instructions, constants, variables and input data when the program is executed] and [auxiliary space required for data operations]
Note: If the auxiliary space required is a constant relative to the input data when the program is executed, the algorithm is said to work in place.
Note: The definition is in the above two sentences
Explanation of time and space complexity: The two aspects of algorithm analysis are mainly time complexity and space complexity. [Generally, when the computing space is sufficient, analyzing time complexity is the main goal to judge the quality of the algorithm]. In addition, excessive Pursue one and the other may worsen performance.
Classification of C statements
Expression statement: An expression plus a semicolon. Executing this statement is to calculate the value of the expression.
Function call statement: function name plus parameter list, plus semicolon
Control statements: There are nine types of control statements in C language, which are divided into three categories: conditional judgment statements, loop execution statements, and jump statements. Detailed explanations will be given later.
Compound statement: A statement formed by multiple statements enclosed by curly braces. Grammatically, it is regarded as one statement. Each statement in the curly braces must be added with a semicolon, but no more can be added after the curly braces.
Empty statement: No operation is performed, only a statement composed of semicolons.
sequential structure
Sequential structure program: In a sequential program, the program runs from top to bottom. After the current statement is executed, the next statement is executed without any judgment. [Usually composed of expressions and function call statements] Because the execution of control statements is not completely executed in sequence, each execution method is different.
Select structure
if statement [when used sequentially, it can be used to judge each step in the process]
Single branch if statement
General form: if (expression) statement;
Explanation: If the expression is true, the following statements will be executed, otherwise they will not be executed.
if...else double branch if statement
General form: if (expression) statement; else statement;
Explanation: If the expression is true, the statement after it will be executed, otherwise, the statement after else will be executed.
if nested statement
Literally, if single branch and double branch are nested, no detailed explanation will be given.
Note: When there are multiple ifs and elses, if you want to find the corresponding combination, you can search from else, that is, the if closest to else is the corresponding combination.
if multi-branch statement
General form: if (expression) statement; else if (expression) statement; ...else statement;
Explanation: Which expression is true, the following statements will be executed and the multi-branch statement will be jumped out. If both are false, the last statement is executed and the multibranch ends.
switch statement (can also be used to call functions)
General form: switch (expression) {case constant expression: statement; break;...default: statement; break;}
Notice
1. The expression in switch must be of integer or character type.
2. Switch execution sequence: judge the value by calculating the value of the expression in parentheses and the constant expression, and then execute the statement after the case. If there is a break, jump out of the switch statement. If not, execute downward. If there is no break, All subsequent statements will be executed.
Third, there can be multiple statements after case without using curly braces.
Four. It's best to have a jump statement that stops execution.
Conditional operators and conditional expressions
Note: The priorities are different, if is the highest, switch is second.
Loop structure
while statement
General form: while (expression) statement;
Explanation: If the expression is always true, the corresponding statement will always be executed. If the expression cannot always be true, an infinite loop will occur. Therefore, the expression of the loop must be false, or there must be a break statement after the corresponding statement.
Note: Expression positions are generally relational expressions and logical expressions, but they can also be other types of expressions. For example, self-added, relationship, 1 and 0.
do-while statement (with if statement, can exit under specific conditions)
General form: do{statement;}while (expression);
Explanation: It is very similar to whlie, but there are some differences in form and execution methods. The while loop is judged first and then executed, while this kind of statement is executed once and then judged. It is this execution method that makes it less applicable than the while statement.
for statement
Note: The above three types of loops can be nested in each other. Among them, the three loop statements have different ranges, for is the largest, while is the second, and do-while is the last.
Note: The above only provides partial organization and overall ideas. Loop statements have a lot of flexibility. It is recommended to gradually master them during use.
Jump statement
break statement: often used in loop bodies and switches, but cannot be used to interrupt if statements
continue statement: can only be used in loop bodies, and is often used in conjunction with if statements
goto statement
General form: goto statement identifier;
Explanation: Execute the statement marked by the symbol, generally used in conjunction with the if statement
return statement
Note: If it has returned, it will jump out of the loop directly.
Note: The use of jump statements makes selection structures and loop structures more flexible. The selection structure and loop structure are composed of a selection statement and a loop statement, plus a jump statement. The three are called control statements.
Structure and its extensions
Definition of structure
definition form
struct structure name {data type variable name;...};
How to use typedef [Help on the definition and use of structure variables]
When defining a structure: typedef struct structure name {data type variable name;...} new data type name;
Note: In the above use process, the structure name is omitted, which does not affect the result. However, the structure name cannot be used when defining the structure variables because you omitted it.
Use after definition: typedef data type or data type name [such as int and struct structure name] new data type name
Description [Notes on structure definition]
1. Structure members can be any basic data type. In addition, they can also be array and pointer types.
Second, the size and number of structures must be certain, and dynamic structures cannot be defined [not supported in C language]
Third, a structure can be defined in multiple nests, but it cannot be defined recursively [use the structure name to define the structure members in the structure]
4. The names of structure members cannot be the same.
5. You can use the structure name to define pointer variables in the structure, and the pointer variable can point to the structure variable.
Structure variable
Definition: We have defined the structure type ourselves. When we use it to define variables, we call it a structure variable, similar to the way basic data types are defined.
Features: From the definition, we can know that the defined structure does not occupy storage space, but when we use it to define structure variables, the system will allocate storage space.
definition form
First, define the structure first [you can choose to use typedef here], and then define the structure variables by adding the variable name to the struct. Because it is defined separately, you can use the new name after ty to define it. These two methods belong to the [sequential category]
2. When defining the structure, define the structure variables [write the variable name directly after the curly braces, and use commas to separate multiple variables]. At this time, the structure variable name can be omitted, but there are restrictions. Please refer to the structure definition. Related concepts. These two methods belong to the [simultaneous category]
Initialization [not initialized, structure variables are automatically 0]
General form: many forms, that is, the defined structure - [structure type] structure variable name = {initial value table};
Specifically: Define the structure first, and initialize the [structure variable] while defining the [structure variable]. Or, define the structure and define and initialize the structure variables at the same time. In the definition and initialization process of the former, if you do not use typedef to establish an alias, you cannot omit the structure type and directly select the variable name for definition.
Explanation: The so-called many forms roughly divide the definition and initialization process into two categories, [sequentially] and [simultaneously], both of which have their own characteristics. [sequentially] can be used with typedef, and [simultaneously] can choose to omit the structure name.
Note: Initialization and the definition of variables are closely related. When initialized through [assignment operation], the definition and initialization are inseparable, [but basic types can be used, this is also the difference]. In addition, [in the initial value table] The order must be consistent with the order of the members in the structure, and there must be no mistakes]
citation form
Member operator: structure variable name. member name
Pointer plus value operator: (*pointer variable name).member name
Pointer plus member selection pointer: pointer variable name -> member name
Note: It cannot be quoted as a whole. It can only be used by referencing some variables through the above three methods. It has the function of an ordinary variable, and when it is referenced, it can only be used as a whole first and then as a part.
Pointer to structure variable [After consideration, this part was chosen to be placed in the pointer section]
Structure array
Features: It has the characteristics of both arrays and structure variables.
Definition: The definition method is consistent with the definition of structure variables, one after another or at the same time.
General form: struct structure name structure array name [size]
struct structure variable name { } structure array name [size]
Initialization: It is still similar to the definition requirements of structure variables. It is closely integrated with the array definition of the structure and cannot be separated [that is, it cannot be defined first and then initialized through assignment operation, you can use scanf]. For the form, please refer to the initialization of structure variables and the multi-dimensional array assignment method.
Reference: Use array subscripts and member operators to reference specific variables in the array. Each part of the array can be assigned a value as a whole, for example, a[0]=a[1]. Partial assignment can also be performed on members, but their types must be the same, for example, a[0].name=a[1].name.
Example diagram to verify the above problem
Several example diagrams explaining definition and initialization
All initializations in the structure, in addition to definition, can also be initialized through the format control input function scanf.
When definition and initialization are initialized through assignment operation, the two are inseparable. It can be done through scanf. The example is shown above.
community
Definition format: union <union name>{<member list>}
Features: The largest variable in the member list is used to open up the same space for each member variable. After initialization, different forms of a value are stored in the member list.
Supplement: Other methods are exactly the same as the structure
Concepts related to variable storage
variable scope
Definition: The valid range of a variable is called the scope of the variable. When a function is called, the formal parameters will only be allocated space when the function is called. Therefore, the variable does not always exist, and the results of different variables are different.
Key point: The regulation of variable scope naturally creates the problem of having the same name. Variables with the same name are not related in [different definition scopes].
local variables
Definition: Variables defined within a function or in a compound statement are called local variables
Valid scope: Local variables are only valid within the function or compound statement in which they are defined. There is no priority between the two. If there is a compound statement in the function, it will only take effect in one of them according to the defined scope.
Global variables (external variables)
Definition: A global variable is a variable defined outside all functions and can be shared by all functions in the same program. When it changes, only the global variable with the same name in the compound statement in the function is not changed.
Valid range: from the defined position to the end of the program.
Note: The use of global variables will reduce the readability of the program, so try not to define global variables.
Storage class and life cycle of variables
Reason: According to the life cycle of variables, they can be divided into static storage variables and dynamic storage variables. Static storage variables are variables that have fixed storage space allocated when the program is running. Dynamic storage variables are variables that allocate storage space as needed during runtime. They are clearly defined and better understood.
Static storage variables
Scope: global variables, static local variables
Life cycle: When the program is executed, space is allocated and will be released after the entire program is completed.
Dynamic storage variables
Scope: automatic variables, formal parameter variables, interrupted field data
Life cycle: From the time the function is called to the end, it runs through the entire execution process of the function.
Automatic variable explanation: refers to local variables that are not declared using static
Explanation of formal parameter variables: refers to parameters in the form of functions
Interrupt context data interpretation: context guarding and return values for function calls
variable storage class
Explanation: When defining variables, we usually use data type definitions, but variables also have storage categories. In C language, variables have two attributes, data type and data storage type.
The complete definition form of the variable: storage category data type identifier variable name;
automatic variable (auto)
Definition: When defining a local variable, if auto is used or the storage category is not specified, the system will default it to an automatic variable, allocate space for it, and place a dynamic storage area.
Scope: starts from the definition position and ends at the definition function scope or compound statement.
Register variable (register)
Reason: Due to the high frequency of use of some variables, for the sake of operating efficiency, the system will save the value of the variable in the register in the CPU.
Definition: A special automatic variable.
limit
Can only be variables of char, int, and pointer categories
Only variables and parameters defined in functions can be defined as register variables
The current compilation system can already automatically identify these variables and put them into register variables.
static variables
Definition: Variables defined using the keyword static
static local variables
Definition: Variables defined within a function or compound statement using the keyword static
Scope: The scope remains unchanged, and the life cycle changes to the execution process of the entire program.
static global variables
Definition: Use statically declared variables. However, after declaration, this global variable can only be used in this source file and loses part of its role as an external variable.
external variables (extern)
Definition: Variables defined outside all functions
Scope: from the definition position to the end of the entire program. If you want to use external variables before the definition position, you can use extern to declare the external variable at the reference position, thus expanding the scope of scope.
Note: In other source files, declaring this external variable can be used in other source files.
File operations
Document overview
File: It is not only an ordered collection of related data identified by a file name, but also a unit of data managed by the operating system.
Classification of files [Files are generally stored on external media and are not called into memory until they are used. Different angles lead to different classifications of files]
【1】From the user's perspective, files can be divided into device files and ordinary files.
【2】From the logical structure point of view, files can be divided into record files and streaming files.
【3】From the perspective of encoding method, files can be divided into text files and binary files.
file pointer
Note: In C language, access to files is achieved through file pointers.
Pointer to file type: The FILE type in C language is a structure type used to store information about files. It is defined in <stdio.h>
File structure pointer: In C language, all external devices are treated as files, called device files.
Opening and closing files
Note: When a C language program performs file operations, it must follow the operation process of "Open" -> "Read and Write" -> "Close". The file cannot be read or written without opening it, and system resources will be exhausted if it is not closed.
Opening the file [returns NULL if the operation fails]
Function: fopen
Format: file pointer name=fopen (file name, file open mode)
[File pointer name] must be a pointer variable declared as FILE type
[File name] can be a string constant or a character array.
[Open file mode] refers to the file type and operation requirements, as follows
Example
file closing
Note: After using the file, you should use the fclose function to close it to prevent the file from being lost or the file being misused again.
Form: fclose (file pointer)
[1] [The closing operation of the file will cause the file pointer to no longer point to the FILE structure corresponding to the file, thus disconnecting the file]
【2】【When writing data to a file, the data will be put into the buffer first. The buffer content will not be sent to the disk until the buffer is full. If it is not full, the buffer content will not be sent. Closing the file will force the buffer content to be sent. 】
【3】【Return 0 for normal file operation, otherwise return EOF】
Reading and writing files
[Explanation]: C language provides many functions for file reading and writing. The difference between them is that the reading and writing units are different. They are all defined in the header file stdio.h.
Character reading and writing functions: fgetc and fputc
String reading and writing functions: fgets and fputs
Data block reading and writing functions: freed and fwrite
Formatted input and output functions: fscanf and fprinf
Word input and output functions: getw and putw
File location [excluding specific operation functions]
File error checking
data structure
Definition: A collection of data elements that have one or more specific relationships with each other. It can also be considered as a collection of structured data elements.
Two levels of data structure
Logical structure: a data model abstracted from actual problems
Division 1
Linear structures: stack, queue, linear list, array
Nonlinear structures: trees, graphs, sets
Division 2
Set: Data elements have no other relationship except that they are in the same set.
Linear structure: There is a one-to-one relationship between data elements.
Tree structure - there is a one-to-many hierarchical relationship between data elements in the structure
Graph structure - there is a many-to-many relationship between data elements in the structure
Storage structure (physical structure): How data elements and their relationships are stored in memory
Sequential storage: [requires all elements to be stored in continuous storage space in sequence], using the location of elements in the memory to represent the logical relationship between elements. Usually represented by an array.
Chain storage: [Data elements are not required to be stored in continuous storage space, but the data items in each data element are stored in continuous space], and a pointer field needs to be attached to each node. The address used to store subsequent elements.
abstract data type
Definition: It refers to the mathematical model defined by the user to represent the application problem, and the sum of a set of operations defined on this model.
Including: data objects, a collection of relationships on data relationships, and a collection of basic operations on data objects.
linear table
Sequence table
Definition: A finite sequence composed of n data elements with the same data characteristics is called a linear table. When n equals 0, it is called an empty list.
Features
There is only one data element called "first" and "last".
Each element has only one direct predecessor except the first.
Each element has only one immediate successor except the last one.
Sequential storage representation of linear table [sequential table]
Definition: Use a set of [storage units with consecutive addresses] to sequentially store the data elements of a linear table, also called the sequential storage structure or sequential image of a linear table
Features: Data elements that are logically adjacent are also adjacent in physical order.
Note: Since the sequence table is continuous, any data element can be accessed as long as the first address of the linear table is confirmed. , so the sequential storage structure of the linear table is a [random access] storage structure.
Supplement: Since high-level programming languages also have random access characteristics, arrays are usually used to describe the sequential storage structure in the data structure. Here, since the length of the linear table may vary depending on the problem, the linear table can be represented by a dynamically allocated one-dimensional array in C language.
Implementation of the basic operations in the sequence table [For the following operations, please set the conditions to determine whether they are legal or not. If they are not legal, an error will be returned]
Initialization: The initialization of the sequence table is to construct an empty sequence table, and determine whether the linear table is an empty table by judging whether the length is 0.
Value: Get the value of the i-th element of the linear table through the given position number i. That is, the array subscript i-1 elements.
Insertion: Insert a new element into the i-th position in the table, turning the linear table of length n into a linear table of length n 1. [You also need to determine whether the linear table is full]
Delete: Delete the i-th element in the list and reduce the length of the linear list by one.
defect:
linked list
Data and related concepts
1.1 Research content of data structure
non-numeric value, characteristic, operation
is to enable computers to perform non-numerical processing more efficiently,
1.2 Basic concepts and terminology
1. Data
Definition: All [symbols] that can be input into the computer to [describe objective things]
Classification
numerical data
non-numeric data
2. Data element (element): the basic unit in data, also called node (node)
3. Data item: The smallest unit that constitutes a data element in the data and has independent meaning and is indivisible.
Scope: Data>Data Object>Data Element>Data Item (scope included)
Data object: Data elements with the same properties, which are subsets of data.
picture
Definition: It consists of a finite non-empty set of points and a finite set of edges. If the edge set is a directed edge, the graph is called a directed graph. If the edge set is an undirected edge, the graph is called an undirected graph. picture.
basic terminology
Subgraph: A graph formed by selecting some of the existing points and edges in a given graph and following the connection method in the given graph.
Undirected complete graph and directed complete graph
1# For an undirected graph, if it has n(n-1)/2 edges, the graph is called an undirected complete graph.
2# For a directed graph, if it has n (n-1) arcs, the graph is called a directed complete graph.
Sparse graphs and dense graphs: A graph with few edges or arcs is called a sparse graph, and the opposite is called a dense graph [strongly subjective, the judgment standard is determined by people]
Quanhe.com
Weight: In practical applications of graphs, values are marked on the edges. These values represent the cost or cost of going from one point to another, which is called weight.
Net: A graph with authority is called a net
Adjacent points: Two points are adjacent through a common edge, which can also be said to be associated with the two points.
Degree, in-degree, out-degree
Degree: the number of edges connecting the point. In a directed graph, the degree is equal to the sum of out-degree and in-degree.
Out-degree: In a directed graph, the edge going out from this point
Entry: In a directed graph, the edge entering from this point.
Path and path length
Path: from the starting point to the end point, all vertex sequences. If the graph is a directed graph, the path is also directed.
Path length: The number of edges or arcs passed along a path.
Loop or Loop: A path whose first and last vertices are the same is called a loop or loop.
Simple path, simple loop (simple loop)
Simple path: A path whose vertices do not repeat in the sequence is called a simple path
Simple loop or simple ring: A loop whose vertices do not repeat except the first and last vertex is called a simple loop or simple ring.
Connectivity related concepts
Connected: In [undirected graph], if there is a [path] between vertex v and vertex v1, it is called connected [the vertices themselves can also be considered connected].
Connected graph: If any two vertices are connected, the graph is called a connected graph.
Connected component: a maximal connected subgraph in an undirected graph.
Strongly connected graph: In [directed graph], if there is a path between any two vertices [these two points are not equal], then the graph is called a strongly connected graph.
Strongly connected component: in a directed graph, maximally connected subgraph
The spanning tree of a connected graph: first it is a connected subgraph, and then it contains all the vertices in the graph, but only n-1 edges.
Directed tree: a directed graph in which one vertex has an in-degree of 0 and the remaining vertices have an in-degree of 1.
Generative forest: composed of several directed trees.
Graph storage structure
Adjacency matrix: is a matrix that represents the adjacent relationship between vertices
Rule: If there is a path between adjacent vertices v(i) and v(j), the path is represented by 1 at the position determined by i and j in the finite set of edges of the graph, otherwise it is represented by 0.
advantage
You can clearly know whether there are edges between adjacent vertices
It is convenient to calculate the degree of each vertex. In an undirected graph, the sum of the elements in the i-th row is the degree. In an undirected graph, the sum of the elements in row i is the out-degree, and the sum of the elements in column j is the in-degree.
shortcoming
Inconvenient to add and delete vertices
It is not convenient to count the number of edges. All elements need to be scanned, and the time complexity is Q(n^2).
High space complexity [especially a waste of time for sparse graphs]
If it represents a network, each connected position is represented by a weight, otherwise, an infinity symbol is used.
Adjacency list: It is a linked storage structure of the graph
rule
advantage
Easy to add and delete vertices
It is convenient to count the number of vertices and edges, and the time complexity is Q(n e)
High space efficiency [suitable for sparse graphs]
shortcoming
It is not convenient to determine whether a vertex has an edge.
It is not convenient to calculate the edges of the directed graph.
Graph traversal
Depth first search [rules]
Starting from a certain node in the graph, visit that node
Starting from the node just visited, look for unvisited adjacent points, and then visit it. Repeat this step until the visited node has no adjacent points.
If the point has no unvisited adjacent points at this time, return to the last visited node. If the node has an unvisited node, visit it, and then continue to return. on the contrary. Return directly until all nodes are visited
Breadth first search [rules]
Starting from a certain vertex of the graph
Access the adjacent points of the point. If there are multiple adjacent points, access laterally.
Then, based on the principle that the node visited first is greater than the priority of the node visited later, subsequent nodes are visited until all nodes in the graph are visited.
Application of diagrams
minimum spanning tree
Prim's algorithm [added point method]
For existing connected networks, we first specify a set of edges [after constructing the minimum spanning tree, it is the set of edges], and then specify a set with only [the first vertex].
Take out all the vertices in the connected graph and place them according to their corresponding positions
Starting from the first vertex, in the given connected graph, find the adjacent edge with the smallest weight [and the point reached by this edge must not be in the concentration of joining points] and connect it in the original way [this edge joins the edge] Set], and then repeat this step starting from the vertex reached by the edge [this point joins the set of points].
If there are multiple edges with the same weight when selecting an edge, just select any edge at this time.
Kruskal's algorithm [Additional edge method]
For existing connected networks, sort the weights in them from small to large.
Take out all the vertices in the connected graph and place them according to their corresponding positions
Take out the edge with the smallest weight and connect it according to its original position on your own graph. If the newly added edge will cause a loop, discard the edge and choose the next edge with a smaller weight.
Shortest path [In a weighted directed graph, it is customary to call the first vertex the source point and the last vertex the end point.
The shortest path from a source point to other source points [Dijkstra's algorithm]
For existing nets, divide the vertices into two groups
A group is a set containing only source points, named S
A set is all points excluding the source point
The algorithm is based on the increasing order of the shortest path length from the source point to other vertices. If the shortest path length from the point to the source point ranks third, then the point is the third point added to the set S.
AOV-Net [a directed graph using vertices to represent activities and arcs to represent activity priority relationships]
An acyclic directed graph is called a directed acyclic graph. A directed acyclic graph is an effective tool for describing the process of a project or system.
[Introduction] In the AOV-net, there should be no directed cycles. The detection method is to perform topological sorting on the given net. If all the vertices are in the topologically sorted directed sequence, then the AOV-net must not exist. ring.
From vertex v(i) to v(j), if there is a directed path, then v(i) is said to be the predecessor of v(j). If there is an arc in the network, it is called a direct predecessor.
Topological sorting [Arrange all the vertices in the AOV-net into a linear sequence that satisfies: If there is a path between vertex v(i) and vertex v(j) in the AOV-net, then v(i) must be in v(j)before]
In a directed graph, select a point that has no direct predecessor and output it
And delete the point and the arc ending at the point in the directed graph
Repeat the above steps until there are no predecessor-less vertices.
If the number of points output at this time is less than the number of vertices in the directed graph, it means that there is a cycle in the directed graph. Otherwise, it is a topologically sorted directed sequence.
AOE-Net [Weighted directed acyclic graph, using edges to represent activities, vertices to represent events, weights to represent the duration of the activity, each event represents that the activity before it has been completed, and the activity after it can start]
It is usually used to represent a project. The entire project has only one completion point and one end point. Therefore, under normal circumstances, there is only one point with an in-degree of 0 in the network, which is called the source point. There is also only one point with zero out-degree, which is called the sink point.
Weighted path length: In AOE-net, the sum of the weights of each arc on a path
Critical path: the path with the longest weighted path length from the source to the sink.
Critical activities: edges on the critical path.
critical path solution process
Topological sorting to find the earliest occurrence time of an activity
Inverse topological sorting to find the latest time when an activity occurs
If these two times are the same, it is a critical activity
Each path from the source to the sink formed by key activities is a critical path. There may be more than one critical path.
Trees and Binary Trees
Tree [is a finite set with n nodes, n is greater than or equal to 0]
Explanation: When n equals 0, it is called an empty tree, otherwise it is a non-empty tree
Definition of non-empty tree
There is only one node called the root
Nodes other than the root node can be divided into m disjoint finite sets. Each set itself is a tree and is called a subtree of the tree.
Understanding: The structure definition of tree is a recursive definition, that is, the definition of tree is used in the definition of tree. Trees can also have other representation forms, [nested set form], [generalized table form], [concave representation]
Basic terminology for trees
Node: an independent unit of the tree, containing a data element and [several branches pointing to its subtrees] (? - such as in chain storage, pointers to the left and right children, and variables for storing data)
Degree of node: The number of subtrees owned by a node is called the degree of the node [number of children owned by the node]
Degree of the tree: the maximum value of each node degree, that is, compare the degrees of all nodes and take the maximum value
Leaf [or terminal node]: node with degree 0
Non-terminal nodes: Nodes with a degree other than 0 are called non-terminal nodes or branch nodes. In addition to the root node, branch nodes are also called internal nodes
Parents and children: A node and the root of its subtree are called the children of the node. Correspondingly, the node is called the child's parents.
Ancestor: all nodes on the branches from the root to the node
Descendants: Any node in the subtree rooted at a certain node is called a descendant.
Level: Starting from the definition of the tree, the root is the first level and the children of the root are the second level. The level of any node in the tree is equal to the level of its parent node plus one.
Cousins: Nodes whose parents are at the same level are called cousins
Depth of tree: The maximum level of nodes in the tree is called the depth or height of the tree
Ordered tree and unordered tree: If the subtrees of the nodes are regarded as ordered from left to right, it is called an ordered tree, otherwise it is an unordered tree [probably, if the specified position cannot be changed, then in this tree The position of each node cannot be changed]. In an ordered tree, the root of the leftmost subtree is called the first child, and the rightmost child is called the last child.
Forest: It is a collection of m disjoint trees, m is greater than or equal to 0. For each node in the tree, the set of its subtrees is called a forest.
Key point: The sum of the degrees of all nodes in the tree is equal to the summary point minus 1 [except for the root node, every node will participate in the calculation of the number of degrees]
tree storage structure
parent representation
Description: The characteristic of storing a tree in a set of continuous storage units makes it easy to find the parents of a node, but finding the child of a node requires traversing the entire structure.
Each node contains a data field and a parent field. The latter stores the subscript of the parent node, as shown in the figure.
child representation
Binary tree [a set composed of n nodes, n is greater than or equal to 0]
The difference between a binary tree and a tree: Each node of a binary tree has at most two subtrees. The subtrees are divided into left and right subtrees, and their order cannot be reversed.
Definition [Tree terms are basically applicable to binary trees]
There is only one root node
Except for the root node, other nodes are divided into two disjoint subsets, called left subtree and right subtree respectively, which are also binary trees.
Properties of binary trees
Property 1: There are at most 2^i-1 nodes in the [i]th level of the binary tree (i is greater than or equal to 1) [equivalent to a geometric sequence with 1 as the first term and 2 as the common ratio]
Property 2: A binary tree with depth k has at most (2^k)-1 nodes (k is greater than or equal to 1) [equivalent to a geometric sequence with 1 as the first term and 2 as the common ratio. This is the sum of the first n terms. 】
Property 3: For any binary tree, the number of terminal nodes is equal to the sum of the nodes with degree 2 plus 1
Full binary tree: a binary tree with depth k and the number of nodes is 2^k minus 1 [equivalent to the degree of all nodes except the root node and the 2^i-1 terminal nodes at the highest level are 2]
Complete binary tree: A binary tree with n nodes of depth k, if and only if each of its nodes corresponds to the nodes numbered from 1 to n in the full binary tree of depth k. [The difference from a full binary tree lies in the number of nodes]
Property 1: A complete binary tree with n nodes whose depth is the logarithm of n with base 2 plus one
Property 2:
Binary tree storage structure
Sequential storage structure [only applicable to complete binary trees, general binary trees can also be used, but it is a waste of storage units]
Explanation: The sequential storage structure uses a continuous storage unit to store elements. In order to reflect the logical relationship between nodes, the nodes must be stored according to certain rules.
Storage method: For a complete binary tree, it is stored from the root node in hierarchical order, from top to bottom, and from left to right. The general storage method of binary trees is that, compared with the complete binary tree, the corresponding positions without nodes are represented by 0 when stored.
chain storage structure
Each node contains a data field and pointer fields 1child and rchild pointing to the left and right children. This type of linked list is called a binary linked list.
Sometimes, in order to easily find the parents of the child node, you can add a pointer field [parent] pointing to the parents. This kind of linked list is called a three-pronged linked list.
The head pointer of the linked list points to the root node
Binary tree traversal
Preorder traversal of a binary tree
Visit the root node first
Then traverse the left subtree in order
Last order traverse the right subtree
Inorder traversal of a binary tree
In-order traversal of left subtree
access root node
In-order traversal of right subtree
Postorder traversal of a binary tree
Postorder traversal of left subtree
Postorder traversal of right subtree
access root node
linear table
Definition: A [finite] sequence of n (n>0) [elements] with [same data characteristics] is called a linear table.
Note: The number of elements n in the linear table [n>0] is defined as the length of the linear table. When n is equal to 0, it is an empty table.
Features [Summary: The uniqueness of the head and tail, as well as the fact that the head has no front drive and the tail has no rear drive. 】
There is only one data element called [first]
There is only one data element called [last]
Except for the first element, each data element in the structure has only one predecessor
Each data element in the structure, except the last element, has exactly one successor
Linear table type definition
Sequential representation and implementation of linear tables ([Sequential storage structure] [Sequential image])
Definition: refers to using a set of continuous storage units to store data elements of a linear table in sequence
Features: Logically adjacent elements are also structurally adjacent, that is, the logical and physical structures correspond. It is a random storage structure.
Operation [At the same time of initialization, its continuous storage space has been opened up. We can directly represent each position in the array (for example, L.elem[i]=e), because the pointer variable in the structure points to the first address of the space. , equivalent to the array name. 】
Initialization: Dynamically open a set of continuous storage spaces, determine whether the opening is successful, then set the length of the linear table to 0, and return the corresponding judgment value
Insertion: first judge the rationality of the insertion position, move the element at the corresponding position, then insert the data element at the corresponding position, then add 1 to the table length, and return the corresponding judgment value.
Value: To determine the rationality of the value, just take the value of the corresponding position directly.
Delete: first judge the rationality of the deleted position, then directly delete the value at the corresponding position, and return the deleted value, move the values on both sides, then reduce the length of the linear table by one, and return the corresponding judgment value.
Empty and destroy: The former is to set the length of the linear table to 0, and the latter is to release the opened space
understanding diagram
Linked representation and implementation of linear tables ([non-sequential image] [chained image]) [logically adjacent, not required to be equal in physical location]
Definition of chained storage structure: A set of arbitrary storage units stores data elements of a linear table. This set of storage units can be either continuous or discontinuous.
Features: Due to the storage structure, element processing must start from the head pointer, so it is also called a sequential storage access structure.
Reason: It is precisely because of this storage structure that in order to express the logical relationship between adjacent data elements, we express the relationship between the two by storing the storage address of the immediate successor in the immediate predecessor. Therefore, in C language, by defining the data domain and pointer fields to form this element, call it a node. The information stored in the pointer field is called a pointer or a chain, and n nodes form a linear table. [Since there is only one pointer field in the node, the linear list composed in this way is called a linear linked list or a singly linked list. 】
explain, distinguish, note
illustrate
Definition of linked list nodes
#! ElemType is a universal type identifier and can be replaced by define as needed
#! For the readability of the program, two structure variables, LNode and *LinkList, are defined. The former is usually used to define the node, and the latter is used to define the head pointer of the linked list.
#! However, a singly linked list is uniquely determined by the head pointer, so the singly linked list can be named using the head pointer. If the head pointer is L, the linked list is also L.
distinguish
Node variables: the name of each node
Pointer variable: pointer to node
Head node: In order to facilitate processing, a node is appended before the first node of the singly linked list, called the head node. The data field can be selectively stored, and the pointer field points to the first node.
Head pointer: a pointer pointing to the first node in the linked list. Different pointing objects are generated depending on whether there is a head node.
Head node: refers to the node that stores the first data element in the linked list.
Note: The second step in the explanation is very important about the two structures having different names but being equivalent.
Create singly linked list
Forward interpolation method: Insert a new node after the head node. After each application for a new node, insert it after the head node. Pay attention to the storage of element values.
Algorithm steps
#! First create a linked list with only the head node
#! According to the number n contained in the linked list, loop n times
#Generate a new node*p
#Enter the element value and store it in the data field
#Insert the new node after the head node
Schematic diagram
Post-insertion method: first have a tail pointer pointing to the tail node of the linked list, and then apply for a new node each time and insert it after the tail node, and then move the tail pointer to point to the position of the new node
Algorithm Description
#! First create a linked list with only the head node, and then initialize the tail pointer to point to the head node.
According to the number of linked lists n, perform n loops
#Apply for a new node*p
#Assign the input element value to the storage structure
#Insert the new node after the tail pointer
#Move the tail pointer to point to the new tail pointer
operate
initialization
【1】Generate a new node as a head node and make the head pointer point to the head node
【2】The data field of the head node is left empty
[Schematic diagram]