中缀表达式转换为后缀表达式及其运算

一.何为中缀表达式和后缀表达式???

  • 中缀表达式:运算符位于两个操作数中间的表达式
    如:1+2*3-5
    运算规则:先乘除、后加减、有括号先算括号

  • 后缀表达式:运算符位于操作数后面的表达式
    如:123+*5-

    • 已经考虑了运算符的优先级
    • 没有括号
    • 只有操作数和运算符,而且越放在前面的运算符优先级越高

二.中缀表达式转换为后缀表达式

工具:一个栈进行运算符优先级比较,一个字符数组存储后缀表达式

具体转换方法:首先从左到右进行遍历表达式:
也是写代码的顺序
遇到操作数,直接输出.
遇到运算符ch,定义一个栈存放运算符
1.栈空,直接入栈
2.ch为左括号,直接入栈
3.ch为右括号,从栈中弹出元素直到遇到左括号
4.对于其他运算符,将ch与栈顶运算符进行比较,
如果ch高于栈顶.则直接入栈
如果ch低于等于栈顶,则从栈中弹出元素直到遇到发现更低优先级的元素(或者栈空)为止,最后ch进栈左括号进栈后,优先级是最低的
5.对象处理完毕,则按顺序弹出并输出栈中所有运算符

//先处理运算符优先级
int prio(char op)
{
	int priority;
	if (op == '+' || op == '-')
		priority = 1;
	else if (op == '*' || op == '/')
		priority = 2;
	else if (op == '(')			//左括号进栈后,优先级最低
		priority = 0;
	return priority;
}
//将中缀表达式str转换为后缀表达式postexp
void trans(string& str,string &postexp)
{
	stacks(100);
	for (int i = 0; i < str.size(); i++)
	{
		//操作数直接放进字符串
		if (str[i] >= '0' && str[i] <= '9')
			postexp += str[i] ;
		else
		{
			//步骤1:栈为空,直接入栈
			if (s.empty())
				s.push(str[i]);
			//步骤2:左括号直接入栈
			else if (str[i] == '(')
				s.push(str[i]);
			//步骤3:右括号,不断弹出直到遇见左括号
			else if (str[i] == ')')
			{
				while (s.top() != '(')
				{
					postexp += s.top();
					s.pop();
				}
				s.pop();		//弹出左括号
			}
			//比较优先级
			else
			{
				//步骤4:优先级<=,则弹出
				while (prio(str[i]) <= prio(s.top()))
				{
					postexp += s.top();
					s.pop();
					//栈空停止
					if (s.empty())
						break;
				}
				//不管优先级是>还是<=,都要将ch入栈
				s.push(str[i]);
			}
		}
	}
	//步骤5:最后处理栈
	while (!s.empty())
	{
		postexp += s.getTop();
		s.pop();
	}
}

三.计算后缀表达式

int compvalue(string &postexp)
{
	stacks(100);
	for (int i = 0; i < postexp.size(); i++)
	{
		
		if (postexp[i] >= '0' && postexp[i] <= '9')
			s.push(postexp[i] - '0');
		if (postexp[i] == '+')
		{
			int x = s.top();
			s.pop();
			int y = s.top();
			s.pop();
			s.push(y+x);
		}
		else if (postexp[i] == '-')
		{
			int x = s.top();
			s.pop();
			int y = s.top();
			s.pop();	
			s.push(y-x);
		}
		else if (postexp[i] == '*')
		{
			int x = s.top();
			s.pop();
			int y = s.top();
			s.pop();
			s.push(y*x);
		}
		else if (postexp[i] == '/')
		{
			int x = s.top();
			s.pop();
			int y = s.top();
			s.pop();
			s.push(y / x);
		}
	}
	return s.top();
}

详解:link中缀转换为后缀过程及其后缀运算
代码:link中缀表达式转换为后缀代码实现

你可能感兴趣的:(中缀表达式转换为后缀表达式及其运算)