您的位置:首页 > 理论基础 > 数据结构算法

C++数据结构与STL--栈的应用--中缀表达式转后缀表达式

2013-07-28 21:32 253 查看
1.输入优先等级和栈优先等级定义:目的,解决右结合表达式问题,例如2^2^2为右结合表达式



2.累计等级与无效表达式分析:








3.使用栈处理相同或较低优先级的运算符

Example:a*b/c+d







4.处理右结合表达式运算符^

Example:a^b^c







5.处理子表达式的左右圆括号。

Example:处理a*(b+c)中的子表达式(b+c)






实现代码:并未包含异常处理

//操作符优先级类

#ifndef op_priority_H

#define op_priority_H

class op_priority

{

private:

int inputPriority; //输入优先级

int stackPriority; //栈优先级

char op; //运算操作符

public:

op_priority()

{

}

op_priority( char ch):op(ch)
//设置运算符的优先级

{

switch(ch)

{

case '+':

case '-':

inputPriority=1;

stackPriority=1;

break;

case '*':

case '/':

case '%':

inputPriority=2;

stackPriority=2;

break;

case '^':

inputPriority=4;

stackPriority=3;

break;

case '(':

inputPriority=5;

stackPriority=-1;

break;

case ')':

inputPriority=0;

stackPriority=0;

break;



}

}

char getOperator()
//返回运算符

{

return op;

}

friend bool operator>=(op_priority &input,op_priority &stack);



};

bool operator>=(op_priority &left,op_priority &right)

{

return left.stackPriority>=right.inputPriority;

}

#endif



//中缀转后缀类

#ifndef in_post_convert_H

#define in_post_convert_H

#include<string>

#include<stack>

#include"op_priority.h"

using std::string;

using std::stack;

class in_post_convert

{

private:

string inExpr; //中缀表达式

string postExpr;
//后缀表达式

stack<op_priority> opStack;//操作符栈

bool isDigt(char c) //判断字符是否为数字

{


return c>='0'&&c<='9';

}



bool isOperator(char c)
//判断字符是否为操作符

{

return c=='+'||c=='-'||c=='*'||

c=='/'||c=='%'||c=='^';

}



void popHeigherEqual(op_priority op)

{

op_priority tem;

while(!opStack.empty()&&(tem=opStack.top())>=op)
//把所有栈操作符的优先级大于输入优先级的操作符出栈

{

postExpr+=tem.getOperator();

opStack.pop();

}

}

public:

in_post_convert(string exp):inExpr(exp)
//构造函数,初始化中缀表达式

{

}





string post() //把中缀表达式转换成后缀表达式

{

for(int i=0;i<inExpr.length();i++)
//从左往右扫描中缀表达式

{

char ch=inExpr[i];

if(isDigt(ch))
//如果是数字,直接写入后缀表达式

{

postExpr+=ch;

}

else if(isOperator(ch)||ch=='(')
//处理操作符和'('

{

op_priority op(ch);

popHeigherEqual(op); //把符合要求的操作符出栈

opStack.push(op);
//把当前操作符进栈

}

else if(ch==')')
//处理')'

{

op_priority op(ch);

popHeigherEqual(op);
//把符合要求的操作符出栈

opStack.pop();
//'('出栈

}

}

while(!opStack.empty()) //把剩余操作符出栈

{

op_priority tem=opStack.top();

postExpr+=tem.getOperator();

opStack.pop();

}



return postExpr;

}

};

#endif

测试程序:

#include<iostream>

#include"in_post_convert.h"

using std::cout;

using std::endl;

int main()

{

string res;

in_post_convert expr(string("3*(4-2^5)+6"));

res=expr.post();

cout<<res<<endl; //3425^-*6+



}

运行解析:




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐