#include "infix2postfix.h"
infix2postfix::infix2postfix(void)
{
}
infix2postfix::infix2postfix(const string& infixExp)
{
this->infix = infixExp;
}
infix2postfix::~infix2postfix(void)
{
}
void infix2postfix::set_priority()
{
oper_prio["#"] = 1;
oper_prio["("] = 2;
oper_prio["+"] = 3;
oper_prio["-"] = 3;
oper_prio["*"] = 4;
oper_prio["/"] = 4;
oper_prio["%"] = 4;
oper_prio["^"] = 5;
oper_prio[")"] = 6;
}
void infix2postfix::setInfixExp(const string& infixExp)
{
infix = infixExp;
}
string infix2postfix::postfixExp()
{
postfix = "";
set_priority();
stk.push("#");
int i = 0;
string input,topstk;//哦~~用string的好处就是可以直接用string的那些成员函数 进行比较 很方便啊!所以在这里topstk并不用char
for(;i<infix.size();)
{
topstk = stk.top();
input = infix.substr(i,1);// 这儿很好啊!
if(!oper_prio[input])//如果是数字的话,就直接写进后缀的字符串
{
postfix+=input;//写进了后缀表达式的字符串
}
else //如果是操作符号的话
{
if (oper_prio[input]>oper_prio[topstk])//如果等待入栈的这个操作符比栈顶的操作符高的话,执行次if句
{
if(input.compare(")")==0)//如果等待入栈的这个操作符是右括号的话
{
while (topstk.compare("(")!=0)//而且如果栈顶并不是左括号的话就一直执行!(也就是在左括号和右括号之间有其它的符号)
{
postfix+=topstk;//将栈顶压入后缀表达式的字符串
stk.pop();//弹出这个栈顶元素
topstk = stk.top();//再度给topstk赋值
}
stk.pop();//把左括号也给弹出,因为没有作用了
}
else //如果等待入栈的这个操作符不是右括号的话,就直接入栈(当然前提是入栈的这个操作符比栈顶的操作符优先级高哦!)
stk.push(input);
}
else//如果等待入栈的这个操作符比栈顶的操作符优先级低的话
{
if(input.compare("(")!=0)//如果等待入栈的操作符不是"("的话,先POP出栈,直到栈顶元素比他低
{
postfix+=topstk;
stk.pop();
continue;
}
else//如果等待入栈的操作符是"("的话,直接入栈
stk.push(input);
}
}
++i;
}
//将剩余的符号全部出栈,放入后缀表达式中
topstk = stk.top();
while (topstk.compare("#")!=0)//直到遇见#号为止
{
postfix+=topstk;
stk.pop();
topstk = stk.top();
}
return postfix;//返回后缀表达式
}