[This article is original to the Technical blog of Silence xuanyuan Sili .]
[This article is for reprinting. for reprinting, please indicate the source in the form of a link .]
[All the articles in this blog have been carefully organized by the bloggers. Please respect the fruits of my work .]
[C Language/C ++] stack and queue stack applications
① Numeric conversion:
It is easy to solve the problem of converting a non-negative decimal integer N to another equivalent B-base number through the "Division B remainder method.
[Example] convert the decimal number 13 to the binary number.
Answer: divide the remainder by two and the remainder is 1, 0, 1, and 1 in sequence. Then, the decimal number is converted to 1101.
Analysis: because the first obtained remainder is the lowest Bit Of the conversion result, and the last obtained remainder is the highest bit of the conversion result, it is easy to use the stack to solve the problem.
The specific algorithm is as follows:
1 # include <STACK>/C ++ use the header file 2 using namespace std to be included in the STACK; // This is also the 3 4 void conversion (int N, int B) 5 {// assume that N is a non-negative decimal integer, and the output is equivalent to the number of B hexadecimal 6 7 stack <int> S; // create an empty stack with an element type of int type 8 while (N) 9 {10 S. push (N % B); // The converted value, starting from the base position to the high position into the Stack 11 N = N/B; 12} 13 while (! S. empty () // return the stack output 14 {15 printf ("% d", S. top (); // print the top element of the stack for 16 S. pop (); // exit the top element of the stack from Stack 17} 18} 19 20 int main () 21 {22 conversion (); 23}
② Evaluate the expression
Expression evaluation is a basic issue in programming language compilation. We will discuss a simple and intuitive method "algorithm priority method"
Arithmetic rule:
1. Left to right
2. multiplication, division, and addition and subtraction
3. Inside and out of brackets
The following two operators have the following priorities:
[Example] the order of Calculation for each step of 4 + 2*3-10/5 is:
4 + 2*3-10/5 = 4 + 6-10/5 = 10-10/5 = 10-2 = 8
Algorithm steps: (assume that the expression ends with the character)
(1) first, create an empty operator stack OPTR, press the expression start character '#' to the bottom of the stack, and create an empty operand stack OPND
(2) read each character in the expression in sequence. If the operand is input to the operand stack, and if the operator is equal to the operator at the top of the operator stack, perform the following operations:
1. If the operator at the top of the stack has a low priority, the new operator will be pushed into OPTR. Execute (2)
2. if the operator at the top of the stack has a high priority, the two top elements of the stack and the operand Stack are moved back to the stack, the values of the expressions composed of three elements are calculated, and then pushed to the operand stack, then proceed with the judgment;
3. If the operator priority at the top of the stack is equal (except for the # Operator, only '(' and ')' are equal), '(' out of the stack; executed (2)
(3) until the entire expression is evaluated (that is, the top element of the OPTR stack and the characters currently read are '#')
Specific Algorithm Implementation:
1 # include <iostream> 2 # include <stack>/C ++ use the header file 3 4 using namespace std to be included in the stack; 5 6 // symbol array 7 char symbol [7] = {'+ ','-','*','/','(',')', '#'}; 8 9 // the priority of the elements in the stack is 10 int in [7] = {3, 3, 5, 5, 1, 6, 0 }; 11 12 // priority of off-stack elements 13 int out [7] = {2, 2, 4, 4, 6, 1, 0 }; 14 15/* 16 * get its array subscript through symbolic characters 17 */18 int get (char c) 19 {20 switch (c) 21 {22 case '+ ': 23 return 0; 24 case '-': 25 return 1; 26 case '*': 2 7 return 2; 28 case '/': 29 return 3; 30 case '(': 31 return 4; 32 case ')': 33 return 5; 34 case '#': 35 return 6; 36 default: 37 return 6; 38} 39} 40 41/* 42 * compare the priority of the intra-stack operators c1 and off-stack operators c2 43 */44 char precede (char c1, char c2) 45 {46 int i1 = get (c1); 47 int i2 = get (c2); 48 49 if (in [i1]> out [i2]) 50 {51 return '>'; 52} 53 else if (in [i1] <out [i2]) 54 {55 return '<'; 56} 57 else 58 {59 retu Rn '='; 60} 61} 62 63/* 64 * calculate the value of the basic expression 65 */66 int figure (int a, int theta, int B) 67 {68 switch (theta) 69 {70 case 0: 71 return a + B; 72 case 1: 73 return a-B; 74 case 2: 75 return a * B; 76 default: 77 return a/B; 78} 79} 80 81/* 82 * calculate the expression value 83 */84 int EvaluateExpression (const char * exp) 85 {86 stack <int> OPND; // operand stack 87 stack <int> OPTR; // operator stack 88 OPTR. push (get ('#'); 89 90 int Flag = 1; // indicates positive and negative numbers 1, indicating positive 0, indicating negative 91 int a, theta, B; 92 93 if (! ('+' = * Exp | '-' = * exp | '(' = * exp | isdigit (* exp ))) 94 {// if it does not start with '+', '-', '(' or one of the numbers, 95 cout <"expression Error 1" <endl; 96 return-1; 97} 98 if ('+' = * exp) 99 {100 exp ++; // point to the next character 101} 102 else if ('-' = * exp) 103 {104 flag = 0; 105 exp ++; // point to the next character 106} 107 108 int index = OPTR. top (); // obtain the 109 while (* exp | symbol [index] of the top element of the operator stack under the array. = '#') // If the top element of the stack is '#' and the current element is null, end computing 110 {111 if (isdigit (* exp )) 112 {// if the current element is a number, calculate the value of the entire operand and press it into the operand stack 113 int sum = 0; 114 while (isdigit (* exp )) 115 {// calculate the operand value 116 sum = sum * 10 + (* exp-'0'); 117 exp ++; 118} 119 if (! Flag) // if it is negative 120 {121 sum =-sum; 122} 123 OPND. push (sum); 124 flag = 1; 125} 126 else 127 {// if it is not a number 128 switch (precede (symbol [OPTR. top ()], * exp) // compare the top operator of the stack with the priority of the current operator 129 {130 case '>': 131 B = OPND. top (); 132 OPND. pop (); 133 a = OPND. top (); 134 OPND. pop (); 135 theta = OPTR. top (); 136 OPTR. pop (); 137 OPND. push (figure (a, theta, B); 138 break; 139 case '<': 140 OPTR. push (get (* exp); 141 if (* exp) 142 {143 exp ++; 144} 145 break; 146 case '=': 147 OPTR. pop (); 148 if (* exp) 149 {150 exp ++; 151} 152 break; 153} 154} 155 index = OPTR. top (); 156} 157 return OPND. top (); 158} 159 160 int main () 161 {162 char c [50] = {0}; 163 cout <"enter an expression:"; 164 cin. getline (c, 50); 165 cout <EvaluateExpression (c) <endl; 166 167 return 0; 168}
Queue applications
Partner Problems1. Problem Description
Let us assume that at the weekend dance, men and ladies are lined up when they enter the ballroom. At the beginning of the dance, a partner is assigned to each of the men's and women's teams. If the initial number of members of the two teams is different, the unpaired members of the long team will wait for the next dance. We need to write an algorithm to simulate the above-mentioned partner pairing problem.
2. Problem Analysis
Men or women who join the team are also assigned partners. Therefore, this problem has a typical first-in-first-out feature. The queue can be used as the data structure of the algorithm.
In the algorithm, assume that the records of men and women are stored in an array as input, then scan the elements of the array in sequence, and decide whether to enter the men's or women's teams based on gender. After the construction of the two queues is complete, the two teams are sequentially assigned with partners with the current line elements until a queue becomes empty. At this time, if a team is still waiting for the matching person, the algorithm outputs the number of waiting persons in the queue and the name of the waiting person in the queue) it will be the first person to get a partner at the beginning of the next dance.
3. Specific algorithms and related types
1 # include <QUEUE> <span style = "background-color: inherit; font-family:; "> // use the header file to be included in the queue in C ++ </span> 2 3 4 using namespace std; 5 typedef struct 6 {7 char name [20]; 8 char sex; // gender, 'F' indicates female, 'M' indicates male 9} Person; 10 11 void DancePartner (Person dancer [], int num) 12 {// structure array dancer stores dancing men and women. num is the number of dancing people. 13 14 Person p; 15 queue <Person> Mdancers, Fdancers; 16 17 for (int I = 0; I <num; I ++) 18 {// Add the dancer to the Team by gender 19 p = dancer [I]; 20 if (p. sex = 'F') 21 Fdancers. push (p); // enter the Women's Team 22 else23 Mdancers. push (p); // enter men's team 24} 25 printf ("The dancing partners are: \ n"); 26 while (! (Fdancers. empty () | Mdancers. empty () 27 {28 // enter the partner name 29 p = Fdancers. front (); // get the first person in the female team 30 Fdancers. pop (); // output 31 printf ("% s", p. name); // print the team name 32 33 p = Mdancers. front (); // obtain the first man in the men's team, 34 Mdancers. pop (); // 35 printf ("% s \ n", p. name); // print out men 36} 37 if (! Fdancers. empty () 38 {// output the remaining number of ladies and the name of the head lady 39 printf ("\ n There are % d women waitin for the next round. \ n ", Fdancers. size (); 40 p = Fdancers. front (); // get the first 41 printf ("% s will be the first to get a partner. \ n ", p. name); 42} 43 else if (! Mdancers. empty () 44 {// output the remaining number of men and the name of the team leader 45 printf ("\ n There are % d men waiting for the next round. \ n ", Mdancers. size (); 46 p = Mdancers. front (); 47 printf ("% s will be the first to get a partner. \ n ", p. name); 48} 49 else50 {51 printf ("There is not person in the queue! "); 52} 53} // DancerPartners54 55 int main () 56 {57 Person p [] = {" A ", 'F'}, {" B ", 'F'}, {"C", 'M'}, {"D", 'M'}; 58 DancePartner (p, 4); 59}