转自巨巨:
https://www.ocrosoft.com/?p=27
#include <iostream>
#include <stdio.h>
#include <stack>
#include <cmath>
#include <string>
#include <string.h>
//9+(3-1)*3+10/2
using namespace std;
stack<char> sop;
char s[1200],post[1200];
double res;
void trans()
{
while(!sop.empty())
sop.pop();
int i=0,j=0;
char ch;
while(s[i])
{
ch=s[i];
if(s[i]=='(')
sop.push(ch);
else if(ch==')')
{
while(!sop.empty()&&sop.top()!='(')
{
post[j++]=sop.top();
post[j++]=' ';
sop.pop();
}
sop.pop();
}
else if(ch=='+'||ch=='-')
{
while(!sop.empty()&&sop.top()!='(')
{
post[j++]=sop.top();
post[j++]=' ';
sop.pop();
}
sop.push(ch);
}
else if(ch=='*'||ch=='/')
{
while(!sop.empty()&&sop.top()!='('&&(sop.top()=='*'||sop.top()=='/'))
{
post[j++]=sop.top();
post[j++]=' ';
sop.pop();
}
sop.push(ch);
}
else
{
while(ch>='0'&&ch<='9')
{
post[j++]=ch;
i++;
if(s[i]) ch=s[i];
else break;
}
post[j++]=' ';
i--;
}
i++;
}
while(!sop.empty())
{
post[j++]=sop.top();
post[j++]=' ';
sop.pop();
}
j--;
post[j]='\0';
}
int main()
{
while(gets(s)!=NULL)
{
trans();
puts(post);
}
return 0;
}