Suffix expression evaluate

Source: Internet
Author: User
# Include <iostream>
# Include <stack>
# Include <cstring>
# Include <string>
Using namespace STD;
Int judge (char popx, char X );
Int func (string, int * I );
Int calculate (int x, int y, char Str );
Int main ()
{
Int N, I;
Char A [6000];
Stack <char> STR;
Str. Push ('#');
Cin> N;
While (n --)
{
Cin>;
String substr = "";
Int J;
For (I = 0; I <strlen ();)
{
If (A [I]-'0'> = 0 & A [I]-'0' <= 9)
{
For (j = I; A [J]-'0'> = 0 & A [J]-'0' <= 9; j ++)
Substr + = A [J];
Substr + = '';
I = J;
}
Else
{
If (Judge (Str. Top (), a [I]) = 1)
{
Substr + = Str. Top ();
Str. Pop ();
}
Else
If (Judge (Str. Top (), a [I]) = 2)
{
Str. Push (A [I]);
I ++;
}
Else
If (Judge (Str. Top (), a [I]) = 3)
{
Str. Pop ();
I ++;
}
}
}
While (Str. Top ()! = '#')
{
Substr + = Str. Top ();
Str. Pop ();
}
Stack <int> stack1;
Cout <substr <Endl;
For (I = 0; I <substr. Length (); I ++)
{
Int num = 0;
If (substr [I]-'0'> = 0 & substr [I]-'0' <= 9)
Stack1.push (func (substr, & I ));
Else
{
Int num1 = stack1.top ();
Stack1.pop ();
Int num2 = stack1.top ();
Stack1.pop ();
Stack1.push (calculate (num2, num1, substr [I]);
}
}
Cout <stack1.top () <Endl;
Stack1.pop ();
}
}
Int judge (char popx, char X)
{
If (popx = '*' | popx = '/')
{
If (x = '*' | x = '/' | x = '+' | x = '-' | x = ') ') // output
Return 1;
Else
If (x = '(') // inbound Stack
Return 2;
}
Else
If (popx = '+' | popx = '-')
{
If (x = '*' | x = '/' | x = '(')
Return 2;
Else
If (x = '+' | x = '-' | x = ')')
Return 1;
}
Else
If (popx = '(' & X! = ')')
Return 2;
Else
If (popx = '(' & X = ')')
Return 3; // move back from the stack
Else
If (popx = '#')
Return 2;
}


Int calculate (int x, int y, char Str)
{
If (STR = '+ ')
Return X + Y;
Else
If (STR = '-')
Return x-y;
Else
If (STR = '*')
Return x * Y;
Else
If (STR = '/')
Return x/y;
}
Int func (string, int * I)
{
Int J, num = 0;
For (j = * I; string [J]-'0'> = 0 & string [J]-'0' <= 9 & string [J]! = ''; J ++)
{
Num = num * 10 + (string [J]-'0 ');
}
* I = J;
Return num;
}

Suffix expression evaluate

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.