#include <iostream> using namespace std; int main() { char a[1000],b[1000]; int i,k; while (cin >> a) { k=-1; for (i=0;a[i]!='\0';++i) { if (a[i]=='-'||a[i]=='+'||a[i]=='*'||a[i]=='/'||a[i]=='(')//判断是否进栈元素 { b[++k]=a[i]; } else if (a[i]>='0'&&a[i]<='9') { cout << a[i]; } if(a[i]==')')//遇到右括号就将进栈的元素出栈到左括号 { while (b[k]!='(') { cout << b[k]; k--; } k--; } if (k>=1&&(a[i]=='-'||a[i]=='+')&&(b[k-1]=='*'||b[k-1]=='/')) //判断元素的优先级,若乘除在加减下面就由下而上出栈 { cout << b[k-1] << b[k] ; k-=2; } } while(k!=-1)//最后将栈内元素清空 { cout << b[k]; k--; } cout << endl; } return 0; }
原文地址:http://blog.csdn.net/zsc2014030403015/article/details/44982839