C language example 03-above, C language example 03-

Source: Internet
Author: User

C language example 03-above, C language example 03-

Sorry, I have to do some work for my family these two days. In addition, the internal capacity and operation volume are also greatly increased. Therefore, writing is slow.

But starting from today. Many of the things I wrote have never been learned before. So the speed will slow down, and the write will be detailed.

The third chapter is data structure, which can be said to be the focus of theoretical learning. At the same time, many schools (including the universities I attended) have offered data structure courses. However, most of the things I talk about are too theoretical, mainly explaining concepts and ideas.

In addition, the data structure is a key subject of professional courses in computer science.

In this chapter, the data structure includes struct, linked list, stack and queue, string and generalized table, binary tree, and graph applications.

Every one is important, so I will repeat it carefully.

3.1 struct

Maybe your C Language Teacher will not explain the linked list, binary tree, etc, but he will certainly explain the use of struct and let you implement code.

What is a struct? In fact, the struct is a standard container. It includes the specified variables.

For example, I set

 1 struct student 2 { 3   char name; 4   int age; 5   float score; 6 };

 

In the program where the struct is located, student is a variable containing three different data types. Of course, you can also think that student is a new data type and a self-defined data type. However, this data type is a specific array, because there are many different data types (arrays can only be the same data type ).

Struct is used to create struct. Other usage will be mentioned in the following example.

Instance 076

Question: enter the name and phone number on the keyboard to end with #. program the function of entering the name and querying the phone number.

Logic: first, a main function is used as the program entry to implement the program running framework. Then, one storage function readin stores data, and the other query function seach stores data.

The main function is nothing more than a definition and initialization variable. Call the storage function to store the input function. Call the query function to output the expected result.

Stores function definitions and initializes variables. Establish a loop to determine whether the input is # and store the data.

Query function definitions and initialize variables. Establish a loop to determine whether the data to be searched matches the current data and whether all data has been traversed.

Program code:

1 # include <stdio. h> 2 # include <string. h> 3 # define MAX 101 4 struct aa 5 {6 char name [15]; 7 char tel [15]; 8}; 9 int readin (struct aa *) 10 11 // note that the variable name of the struct aa is * a, which is a pointer because the struct is called in all three functions. Therefore, you can call a large amount of data between functions conveniently only by using pointers. 12 13 // In fact, when using the pointer as a variable, an aa struct array named a has been created. 14 15 {16 int I = 0, n = 0; 17 while (1) 18 19 // my favorite cycle body setting method, including for (; 1 ;) and then establish relevant judgment conditions in the loop body. 20 {21 scanf ("% s", a [I]. name); 22 if (! Strcmp (a [I]. name, "#") 23 24 // use this judgment statement to determine whether the input is #. (In fact, the assignment and judgment can be implemented in the judgment statement. Although it looks good, but make sure that your logic is correct .) 25 26 // strcmp () checks whether two strings are equal, returns 0 equal, returns 0 equal, returns 0.27 break equal, and 28 scanf ("% s", a [I]. tel); 29 I ++; 30 n ++; 31} 32 return n; 33 34 // return the number of input struct. (A group of data is a struct) 35} 36 void search (struct aa * B, char * x, int n) 37 38 // x is a pointer, in the main function, name is an array name, that is, a pointer. 39 {40 int I; 41 I = 0; 42 while (1) 43 {44 if (! Strcmp (B [I]. name, x) 45 {46 printf ("name: % s tel: % s \ n", B [I]. name, B [I]. tel); 47 break; 48} 49 else50 I ++; 51 n --; 52 53 // In fact, this n is used to calculate whether all struct traversal. But I think I will do it. Although I is in the judgment statement, this statement is always executed if no target is found, as if n is treated as 54 55 outside. // when the judgment statement finds the target, so we don't need him anymore. Because the program is over. 56 57 if (n = 0) 58 {59 printf ("No found! "); 60 break; 61} 62} 63} 64 main () 65 {66 struct aa s [MAX]; 67 int num; 68 char name [15]; 69 num = readin (s); 70 71 // This statement has two functions: 1. returns the readin function to num; 2. the readin function stores data in array s. 72 printf ("input the name:"); 73 scanf ("% s", name); 74 search (s, name, num); 75}

 

Reflection: struct structures will be used in the future, as if int and char data types are common. At the same time, in this program, we learned the simple architecture of functions in the program. In addition, we can fully scale this function. For example, you can store things and find things at ordinary times. The storage and search functions of various programs are large.

3.2 linked list

Generally, the first data structure in this course is a linked list. The first page of many textbooks is the linked list.

"Most of the students lack practical programming experience, and I often ask the candidates to create a simple linked list during recruitment. As a result, many people will not. "

The linked list can be said to be an entry to the data structure application. If this is not the case, it is best not to consider programming-related occupations.

I have read a book and it tells a story at the beginning. That is to say, a new programmer processes website data for the first time and makes an array of 1500 characters and loops to store temporary data. And soon the website went down. Later, the author changed his array into a 1500 circular linked list.

Linked lists dynamically allocate buckets to store data, avoiding space waste. (How many people are struggling with the size of space when using arrays to store data?) at the same time, the storage space of the linked list can be discontinuous, discontinuous, or discontinuous. This creates a lot of conveniences and makes effective use of the storage space.

I will explain every example. (I won't say that I remember the one-way linked list when I saw it ...)

Create a one-way linked list in instance 078

Problem: create a one-way linked list for data input and output.

Logic: A linked list is composed of nodes. Each node is divided into two parts: data domain and pointer domain. The data field is used to store data, and the pointer field is used to store the next node location (a two-way linked list also has a linked list that refers to the previous node ). Generally, 0th nodes are the head nodes of the entire linked list. They are called "head Pointers". Generally, they do not store data and only store pointers pointing to 1st nodes. The pointer of the last node of the linked list is set to NULL as the ending sign of the linked list.

Program code:

1 # include <stdio. h> 2 # include <malloc. h> 3 // malloc is a function used to divide buckets. 4 struct LNode 5 {6 int data; 7 struct LNode * next; 8 // points to the next struct. To form a linked list. 9}; 10 struct LNode * create (int n) 11 {12 int I; 13 struct LNode * head, * p1, * p2; 14 // head indicates the header node. P1, which can be used to obtain buckets and assign values to data domains. P2, as the intermediate pointer to p1, forms the replacement connection of the linked list. 15 int a; 16 head = NULL; 17 // the header node is empty. 18 printf ("Input the integers: \ n"); 19 for (I = n; I> 0; -- I) 20 {21 p1 = (struct LNode *) malloc (sizeof (struct LNode); 22 // malloc (sizeof (struct LNode) indicates the storage space allocated by the LNode. 23 // (struct LNode *) indicates data type conversion, converting the first address of the divided bucket to the variable name (pointer type) of LNode ). 24 scanf ("% d", & a); 25 p1-> data = a; 26 // store data to the p1 struct. 27 if (head = NULL) 28 {29 head = p1; 30 p2 = p1; 31 // process the first node. 32} 33 else34 {35 p2-> next = p1; 36 // The next node of p2 is p1. P2 is p1 in the previous loop. That is to say, p2 is just an intermediate variable temp. 37 p2 = p1; 38 // confirms the origin of p2 in the previous comment. 39 // the specific process is reflected in the description of the variable name. 40} 41} 42 p2-> next = NULL; 43 // the pointer field of the last node is NULL, which serves as the end flag. 44 return head; 45 // return the variable name (pointer) of the struct representing the header node ). 46} 47 void main () 48 {49 int n; 50 struct LNode * q; 51 printf ("Input the count of the nodes you want to creat :"); 52 scanf ("% d", & n); 53 q = create (n); 54 // input, return. 55 printf ("The result is: \ n"); 56 while (q) 57 // q will jump out of The loop only when it reaches The next of The last node and is NULL. A useful tips. 58 {59 printf ("% d", q-> data); 60 q = q-> next; 61 // convert q to output all data. 62} 63 getch (); 64}

 

If you are interested in the mentioned malloc function and related calloc function and free function, you can browse http://blog.csdn.net/shuaishuai80/article/details/6140979.

Reflection: There are several key points for learning this example: 1. do not confuse pointers. Do not confuse the pointer of the struct name with the pointer of next in the structure, although the two sometimes express the same thing;

2. Be sure to fully understand p1 = (struct LNode *) malloc (sizeof (struct LNode); this Code; (explained in the example)

3. Correctly Understand the implementation of p2-> next = p1; and p2 = p1. (It can be understood that the data can be brought in for two to three cycles ).

Create a two-way linked list in instance 079

Problem: create a two-way linked list and output the data in the linked list to the form. enter the name of the student to be searched and delete the name from the linked list, and delete the linked list.

Logic: Actually, logic is quite simple. It is the same as the previous one-way linked list, but it is more than the setting of the successor node. In addition, the search is no different from the ordinary struct array search. To delete a node, You need to modify the settings of the parent node and the successor node of the deleted node. For more information, see the code.

Program code:

1 # include <stdio. h> 2 typedef struct node 3 {4 char name [20]; 5 struct * prior, * next; 6 // you can specify the frontend and successor nodes of a node. 7} stud; 8 stud * creat (int n) 9 {10 stud * p, * h, * s; 11 int I; 12 h = (stud *) malloc (sizeof (stud); 13 // apply for a bucket 14 h-> name [0] = '\ 0 '; 15 // set name to NULL 16 h-> prior = NULL; 17 h-> next = NULL; 18 p = h; 19 for (I = 0; I <n; I ++) 20 {21 s = (stud *) malloc (sizeof (stud); 22 p-> next = s; 23 printf ("Input the % d student 'sname:", I + 1); 24 scanf ("% s", s-> name ); 25 s-> prior = p; 26 s-> next = NULL; 27 p = s; 28 // The method is no different from the one-way linked list, the difference is that there is only one precursor Node. 29 // in some aspects, it is easier to understand with more front-end nodes. 30} 31 p-> next = NULL; 32 // set the successor node of the last node to NULL as the end flag. 33 return (h); 34} 35 stud * search (stud * h, char * x) 36 {37 stud * p; 38 char * y; 39 p = h-> next; 40 while (p) 41 {42 y = p-> name; 43 if (strcmp (y, x) = 0) 44 // determine whether it is the target. 45 return (p); 46 // return the target address. 47 else 48 p = p-> next; 49 // continue the next node detection. 50} 51 printf ("cannot find data! \ N "); 52 // no matching results are returned. 53} 54 void del (stud * p) 55 {56 p-> next-> prior = p-> prior; 57 // make the precursor node of the next node of p consistent with that of the current node of p (in this way, p does not exist in the precursor node. And the linked list is not broken .) 58 p-> prior-> next = p-> next; 59 // make the successor node of the previous node of p consistent with that of the current node of p (so that p does not exist in the back street node. And the linked list is not broken .) 60 // remember: p-> next is the last node of p. P-> prior is the same. 61 // if you cannot understand it, please draw a linked list chart on the draft to make it clear. 62 // the following two sentences of code report errors in some runtime environments. You can change the statements or environments on your own. 63 free (p); 64 // release the p storage space (p does not exist on the linked list. Of course, it cannot occupy space.) 65} 66 main () 67 {68 int number; 69 char sname [20]; 70 stud * head, * sp; 71 puts ("Please input the size of the list:"); 72 scanf ("% d", & number); 73 head = creat (number ); 74 sp = head-> next; 75 printf ("\ nNow the double list is: \ n"); 76 while (sp) 77 {78 printf ("% s ", & * (sp-> name); 79 sp = sp-> next; 80} 81 // The previous values are the same as those of one-way linked lists. 82 printf ("\ nPlease input the name which you want to find: \ n"); 83 scanf ("% s", sname); 84 sp = search (head, sname); 85 // search for the sname address sp through the search function. 86 printf ("the name you want to find is: \ n", * & sp-> name); 87 del (sp); 88 // bring sp to del () function, delete. 89 sp = head-> next; 90 // This sentence is used only for the following while loop. You can delete this statement and set a variable for the following loop. 91 printf ("\ nNow the double list is: \ n"); 92 while (sp) 93 {94 printf ("% s ", & * (sp-> name); 95 sp = sp-> next; 96} 97 printf ("\ n "); 98 puts ("\ nPress any key to quit... "); 99 getch (); 100 // same output principle as one-way linked list. 101}

 

Reflection: two-way linked list and one-way linked list are no different. Remember that a two-way linked list has a prior pointer more than a one-way linked list. Remember to add, delete, move, or modify a two-way linked list.

Instance 080 cyclic linked list

Do you still remember the story about the linked list of the website I mentioned at the beginning. This is the circular linked list.

In fact, there is nothing to say at this time. The cyclic linked list sets the successor node of the last node as the header node.

The operation of the cyclic linked list is basically the same as that of the common linked list. It only determines whether the condition is not p-> whether next is null, but equal to the head node of the linked list when the nodes in the cyclic traversal table are in the algorithm.

Program code: (this is not demonstrated here. The length should not be left for unwanted things .)

Instance 081 double-stranded table reverse

Problem: create a two-way linked list to reverse the node of the two-way linked list, that is, place the last node to the first node, and put the last and second nodes to the second node.

Logic: the creation, input, and output of a two-way linked list are the same as before. For modular operations, a reverse function is created separately to perform reverse operations. The reverse operation is the pointer transformation.

Some code:

1 stud * reverse (stud * head) 2 {3 stud * p, * r, * h; 4 h = head-> next; 5 6 // set h. 7 if (h & h-> next) 8 {9 p = h; 10 r = p-> next; 11 p-> next = NULL; 12 while (r) 13 {14 p = r; 15 r = r-> next; 16 p-> next = h; 17 h-> prior = p; 18 h = p; 19 20 // The intermediate Variable p. The variable r traverses backward from the head of the linked list, and the variable h traverses forward from the tail of the linked list. The Variable p acts as the intermediate variable to transfer the pointer address and reverse the linked list. 21} 22 head-> next = h; 23 h-> prior = head; 24 25 // after the event, complete the chain table. That is, the beginning and end of the linked list. 26 return head; 27} 28}

 

Reflection: to do this, you must not confuse pointers, pointer pointers, and pointer pointers. These three concepts.

There is also a lot of related knowledge, such as reverse output, Joseph ring, element insertion of the linked list, node insertion, Node Deletion, merged linked list, and head insertion to create a linked list. However, I think that if the previous linked list is understood. The following knowledge is nothing more than the basic knowledge version application of the linked list. If necessary, contact me.

Conclusion: In fact, after learning the linked list, we will find out how important it is to learn a good pointer. Especially pointer. If pointers are well learned, the linked list should learn the concept of a linked list, some special functions of the linked list, and common algorithms. Then, some of the subsequent applications are just a matter of course. (This is the linked list application of the previous program .)

Due to the time relationship, so much is written this time. (In fact, this write is much more than before, especially offline debugging .)

Thank you for your appreciation and comments. I also hope that I can meet some friends of interest.

In addition, I may soon write something else.

(I just learned the code to insert this item after the blog Park officially notified me. Pretty good. It is quite sad for me to copy the code and press the Tab after each copy. Thank you .)

Related Article

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.