BBBBB

中缀表达式转为后缀表达式

编辑器加载中...

#include <iostream>
#include
<string>
#include
<vector>
#include
<stack>
using namespace std;


struct oper
{
string op;
int pre;
};

void parse(string s,vector<string> vc)
{
stack
<oper> st;

string str="";
int n=0;
vc.push_back(
"");
for(int i=0;i<s.length();i++)
{
if('0'<=s[i] && s[i]<='9')
{
vc.back()
=vc.back()+s[i];
}
else
{
oper o;
switch(s[i])
{
case ')':
o.op
=')';
o.pre
=0;
break;
case '+':
o.op
='+';
o.pre
=1;
break;
case '-':
o.op
='-';
o.pre
=1;
break;
case '*':
o.op
='*';
o.pre
=2;
break;
case '/':
o.op
='/';
o.pre
=2;
break;
case '(':
o.op
='(';
o.pre
=3;
break;
}
if(st.empty())
{
st.push(o);
}
else
{
if(st.top().pre<o.pre)
{
st.push(o);
}
else
{
while(!st.empty() && st.top().pre>=o.pre)
{


if(st.top().pre==3 && o.pre==0)
{
st.pop();
break;
}
else if (st.top().pre==3 && o.pre!=0)
{
break;
}
else
{
vc.push_back(st.top().op);
st.pop();
}
}
if(o.pre!=0)
st.push(o);
}
}
vc.push_back(
"");
}
}

while(!st.empty())
{
vc.push_back(st.top().op);
st.pop();
}

//vector<string>::iterator itr;
for(int k=0;k<vc.size();k++)
{
cout
<<vc[k];
}
}


void main()
{
string s;
cout
<<"Please input your expression:"<<endl;
cin
>>s;
vector
<string> vc;
parse(s,vc);
}

  

posted @ 2011-09-04 14:48  如是然  阅读(161)  评论(0)    收藏  举报