【基础】中缀表达式求值模板

​//参考老师代码 
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<cmath>
#include<algorithm>
#define Maxn 100000
using namespace std;
int n,m;
stack<int> s1;
stack<char> s2;
inline int strlen_t(char t[])
{
	int cnt=0;
	for(int i=1;i<=Maxn;i++)
	{
		if(t[i]!='\0') ++cnt;
		else break;
	}
	return cnt;
} 
inline int lev(char x)
{
	if(x=='+'||x=='-') return 1;
	if(x=='*'||x=='/') return 2;
	if(x=='^') return 3;
	return 0;
}

inline void calculate(stack<int> &s1,stack<char> &s2)
{
	int y=s1.top();s1.pop();
	int x=s1.top();s1.pop();
	char z=s2.top();s2.pop();
	if(z=='+') s1.push(x+y);
	if(z=='-') s1.push(x-y);
	if(z=='*') s1.push(x*y);
	if(z=='/') s1.push(x/y);
	if(z=='^') s1.push((int)pow(x,y));
}

inline int c(int x)
{
	return x!=0;
}

char str[Maxn];
int sum[Maxn];
int main()
{
	scanf("%s",str+1);
//	cout<<strlen_t(str)<<endl<<strlen_t(str+1)<<endl;
	n=strlen_t(str);
//	printf("%d\n",str[0]);
/*	for(int i=0;i<=n;i++)
	{
		cout<<str[i];
	}*/
	int temp=0;
	bool flag=false;
	for(int i=1;i<=n;i++)
	{
		if('0'<=str[i]&&str[i]<='9')
		{
			temp=temp*10+str[i]-'0';
			flag=true;
		}
		else
		{
			if(flag==true)
			{
				s1.push((temp));
				temp=0;
				flag=false;
			}
			if(str[i]=='(')
			{
				s2.push(str[i]);
				continue;
			}
			if(str[i]==')')
			{
				while(s2.top()!='(')
				{
					calculate(s1,s2);
				}
				s2.pop();
				continue;
			}
			while(!s2.empty()&&lev(s2.top())>=lev(str[i]))
			{
				calculate(s1,s2);
			}
			s2.push(str[i]);
		}
	}
	if(flag==1)
	{
		s1.push(temp);
		temp=0;
		flag=false;
	}
	while(!s2.empty())
	{
		calculate(s1,s2);
	}
	cout<<s1.top()<<endl;
	return 0;
}

​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于中缀表达式,一般需要借助栈来完成。具体的步骤如下: 1. 创建一个运算符栈和一个操作数栈。 2. 从左到右遍历中缀表达式的每一个元素。 - 如果当前元素是操作数,直接将其压入操作数栈。 - 如果当前元素是运算符,分为以下几种情况处理: - 如果运算符栈为空或者栈顶运算符是"(",则直接将该运算符压入运算符栈。 - 如果当前运算符的优先级大于栈顶运算符的优先级,将当前运算符压入运算符栈。 - 如果当前运算符的优先级小于或等于栈顶运算符的优先级,将栈顶运算符弹出,并将其与操作数栈栈顶的两个操作数进行计算,将计算结果压入操作数栈,并将当前运算符压入运算符栈。重复这一步骤直到当前运算符的优先级大于栈顶运算符的优先级。 - 如果当前运算符为")",则依次弹出运算符栈的栈顶元素,直到栈顶元素为"("。将弹出的运算符与操作数栈栈顶的两个操作数进行计算,将计算结果压入操作数栈。 3. 遍历完中缀表达式后,将运算符栈中的剩余运算符依次弹出,并对操作数栈栈顶的两个操作数进行计算,将计算结果压入操作数栈。 4. 遍历完后,将操作数栈中的唯一元素即为中缀表达式结果。 需要注意的是,对于乘法和除法这样的高优先级运算符,要先进行计算再进行压栈操作,而对于加法和减法这样的低优先级运算符,只有在栈顶运算符优先级小于当前运算符时才进行计算。 这就是中缀表达式的基本步骤。通过按照以上步骤运算,可以得到中缀表达式c的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值