#include <stdio.h>
#include <string.h>
#include <stack>
#define N 1000
using namespace Std;
Stack<char> op;//defines the stack of Save operators
Char S1[n],s2[n];
int priority (char ch)//defines the precedence of the operator
{
int num;
Switch (CH)
{
Case ' + ':
Case '-': return 1;
Case ' * ':
Case '/': return 2;
Case ' (':
Case ') ': return 0;
default:return-1;
}
}
int main ()//convert infix expression to suffix expression
{
int T;
scanf ("%d", &t);
Op.push (' # ');
while (t--)
{
scanf ("%s", S1);
int K=strlen (S1);
int top=-1;
for (int i=0;i<k;i++)
{
if (s1[i]>= ' 0 ' &&s1[i]<= ' 9 ')
{//When it's a number
top++;
S2[top]=s1[i];
}
else if (s1[i]== ' + ' | | s1[i]== '-' | | s1[i]== ' * ' | | s1[i]== '/')
{//If the operator at the top of the current operation Fubi a high priority, the current operator is pushed into the stack
if (priority (S1[i)) >priority (Op.top ())) Op.push (S1[i]);
Else
{//The current operator has a small priority, then the operator precedence in the stack is greater than or equal to the current from the stack
while (Priority (Op.top ()) >=priority (S1[i]))
{
top++;
S2[top]=op.top ();//The stack top operator out of the stack
Op.pop ();
}
Op.push (S1[i]);//Then put the current operator into the stack
}
}
else if (s1[i]== ' (') Op.push (S1[i]);
else if (s1[i]== ') ')
{
while (Op.top ()! = ' (')
{
top++;
S2[top]=op.top ();
Op.pop ();
}
Op.pop ();//delete the left parenthesis
}
}
while (Op.top ()! = ' # ')//if the symbol stack is still not empty at this time, all the stacks
{
top++;
S2[top]=op.top ();
Op.pop ();
}
for (int i=0;i<=top;i++)
{
printf ("%c", S2[i]);
}
printf ("\ n");
}
return 0;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Nanyang OJ depressed C small plus (a) topic 257