The individual program design requirements to do a program with computational functions, and to calculate is inseparable from the expression, according to the General People's habit, infix expression is a very common way. However, it is not so convenient for US programmers to compute infix expressions directly, so we usually convert infix expressions.
Whether it is a prefix expression or a suffix expression, the transformation through the tree can be achieved, at the same time, a tree will be able to complete the conversion of the former \ \ suffix expression, so if only the conversion and frequent conversion, it is undoubtedly convenient to build a tree. However, for calculations, conversion is only one step, so we have to consider the efficiency problem, then the stack method is our first choice. The stack is a very interesting data structure, it is characterized by advanced, that is, like a bottle first put in the last thing to come out. Here, due to the characteristics of the stack, so that our infix conversion is very simple, the following is a general introduction to infix expression conversion suffix expression method:
1. When an operand is encountered, output directly to the suffix expression
2. When the stack is empty, operator is encountered, then the operator is pressed into the stack
3. When opening parenthesis is encountered, press the left parenthesis into the stack
4. When the closing parenthesis is encountered, the closing parenthesis is discarded, the fire executes the stack operation, and the elements of the stack are output to the suffix expression until the left parenthesis of the pop-up stack, and the left parenthesis is not output directly discarded.
5. When encountering other operators, that is, subtraction, pops all top-level elements with precedence greater than or equal to the operator, and then pushes the operator into the stack
6. Finally, when the prefix expression is all output or pressed into the stack, the elements in the stack are sequentially stacked and output to the suffix expression.
The infix expression conversion prefix expression method is broadly similar, no longer repeat.
Finally, attach a conversion program.
1 voidChange (std::string inch){ 2 3STD:: stack<Char>Stack; 4 5 for(size_t i =0; I! =inch. Size (); i++){ 6 if(inch[I] = =')' ){ 7 while(true ){ 8 CharTMP =Stack.top (); 9 Stack.pop (); Ten if(TMP! ='(' ){ OneStd::cout <<tmp; A } - Else{ - Break; the } - } - } - Else if(inch[I] = ='+'||inch[I] = ='-'){ + if(Stack.top () = ='*'|| Stack.top () = ='/'){ - while(Stack.top () = ='*'|| Stack.top () = ='/'){ +Std::cout <<Stack.top (); A Stack.pop (); at } -Std::cout <<inch[i]; - } - Else{ -Stack.push (inch[i]); - } in } - Else if(inch[I] = ='('||inch[I] = ='*'||inch[I] = ='/' ){ toStack.push (inch[i]); + } - Else{ theStd::cout <<inch[i]; * } $ } Panax Notoginseng while(Stack.size ()) { -Std::cout <<Stack.top (); the Stack.pop (); + } A}
A summary of the pre-and suffix expressions of infix expressions