The infix expression is used to calculate an expression, such as a calculator.
This is implemented using the stack data structure. First, enter a string to represent an expression, and then store the number with one stack and the storage symbol of the other stack.
If the priority of the current operator is higher than that of the top element of the stack, the incoming operator is added to the stack. If the priority of the current operator is smaller than or equal to the priority of the top element of the stack, two elements are displayed from the digital stack, A symbol pops up from the symbol stack and the calculation result is pushed to the stack (Digital stack );
The Code is as follows:
# Include <iostream>
Using namespace STD;
# Include <cstring>
# Include <stack>
# Include <cmath>
Int judge (char X, char popx );
Int func (int x, char STR, int y );
Int main ()
{
Int W;
Cin> W;
While (w --)
{
Stack <int>;
Stack <char> STR;
Int I, N;
Char s [2000];
Str. Push ('#'); // condition for judging the empty Stack
Cin> S;
For (I = 0; I <strlen (s );)
{
If (s [I]-'0'> = 0 & S [I]-'0' <= 9)
{
Int M [20], J;
For (j = I; s [J]-'0'> = 0 & S [J]-'0' <= 9; j ++) // when calculating a number, because the number may be greater than 10, special computation is required here.
M [J-I] = s [J]-'0 ';
Int sum = 0;
For (int K = j-i-1; k> = 0; k --)
Sum + = m [k] * POW (10, j-i-k-1 );
A. Push (SUM );
I = J;
}
Else
{
If (Judge (Str. Top (), s [I]) = 2) // inbound Stack
{
Str. Push (s [I]);
I ++;
}
Else
If (Judge (Str. Top (), s [I]) = 1) // calculate
{
Int numb1 = A. Top ();
A. Pop ();
Int numb2 = A. Top ();
A. Pop ();
A. Push (func (numb2, str. Top (), numb1 ));
Str. Pop ();
}
Else
If (Judge (Str. Top (), s [I] = 3) // parentheses
{
Str. Pop ();
I ++;
}
}
}
While (true)
{
If (Str. Top () = '#')
{
Cout <A. Top () <Endl;
A. Pop ();
Break;
}
Else
{
Int numb5 = A. Top ();
A. Pop ();
Int numb6 = A. Top ();
A. Pop ();
A. Push (func (numb6, str. Top (), numb5 ));
Str. Pop ();
}
}
}
}
Int judge (char popx, char X) // determine the priority
{
If (popx = '*' | popx = '/')
{
If (x = '(')
Return 2; // directly go to the stack
Else
If (x = '+' | x = '-' | x = ') '| x =' * '| x ='/') // calculate the output stack first.
Return 1;
}
Else
If (popx = '+' | popx = '-')
{
If (x = '*' | x = '/' | x = '(') // directly enters the stack
Return 2;
Else
If (x = '+' | x = '-' | x = ')')
Return 1;
}
Else
If (popx = '(' & X! = ') | Popx = '#')
Return 2; // directly go to the stack
Else
If (popx = '(' & X = ')')
Return 3;
}
Int func (int x, char STR, int y) // calculates the value.
{
If (STR = '+ ')
Return X + Y;
If (STR = '-')
Return x-y;
If (STR = '*')
Return x * Y;
If (STR = '/')
Return x/y;
}
Infix expression evaluate