思路
符号优先级: 乘除>加减>左括号
中缀表达式转后缀表达式
(1)所有数字直接输出
(2)遇到'(',入栈
(3)遇到')',将栈顶元素出栈并输出,直至遇到'(',
'('出栈
(4)当栈内元素优先级不低于栈外元素, 则一直出栈栈顶元素并输出, 然后将该栈外元素入栈。
分为二种情况:
(1)如果栈外'*' or '/', 当栈内元素为'*' or '/' 且 栈不为空, 则一直出栈栈顶元素并输出,而后入栈该栈外元素。
(2)如果栈外为'+' or '-', 当栈内元素不是'(' 且 栈不为空时, 则一直出栈栈顶元素并输出,而后入栈该栈外元素。
最后
(5)将栈内所有元素出栈并输出。
代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int N=1100;
void print()
{
static int flag=0;
if(flag!=0) putchar(' ');
flag=1;
}
int main()
{
char a[N];
gets(a);
int len = strlen(a);
int flag=0;
char s[N];
int top=-1;
for(int i=0;i<len;i++)
{
if(a[i]>='0'&&a[i]<='9')
{
print();
putchar(a[i]);
while((a[i+1]>='0'&&a[i+1]<='9')||a[i+1]=='.')
putchar(a[++i]);
}
if(a[i]=='(') s[++top]=a[i];
if(a[i]==')')
{
while(s[top]!='(')
{
print();
putchar(s[top--]);
}
top--;
}
if(a[i]=='*'||a[i]=='/')
{
while((s[top]=='*'||s[top]=='/')&&top!=-1)
{
print();
putchar(s[top--]);
}
s[++top]=a[i];
}
if(a[i]=='+'||a[i]=='-')
{
while(top!=-1&&s[top]!='(')
{
print();
putchar(s[top--]);
}
s[++top]=a[i];
}
}
while(top!=-1)
{
print();
putchar(s[top--]);
}
return 0;
}