简单的后缀表达式计算

简单的后缀表达式计算

(简单不是指代码简单,而是要计算的表达式简单)

什么是后缀表达式?
百度百科传送门

最简单后缀表达式:

a b +

一眼可以看出结果是 a + b,就是先将前面的数字存起来,遇到运算符,取两个数字,运算,再存起来

  • 使用具有先进后出 好特性 的栈结构去存储运算数

具体做法:

  1. 从左往右遍历表达式
  2. 如果是运算数,进栈
  3. 如果是运算符,在栈中取两个数字做运算

(注意顺序是 第二次取栈顶元素 运算 第一次取栈顶元素)

在这里插入图片描述

代码

这里假设运算的数字都是个位数,只有加减法(实际上任何位数,任何运算符都可以用此方式计算)

#include <iostream>
#include <string>
#include <stack>

using namespace std;

#define char2int(x) ((int)(x - '0'))

int main()
{
	string s;
	cin>>s;
	
	stack<int> st;
	
	for(int i=0; i<s.length(); i++)
	{
		// 数字直接进栈
		if('0'<=s[i] && s[i]<='9')
		{
			st.push(char2int(s[i]));
		}
		// 运算符,取栈顶两数字计算(注意顺序)
		else
		{
			int n2 = st.top();
			st.pop();
			int n1 = st.top();
			st.pop();
			
			char sign = s[i];
			if(sign == '+')
			{
				cout<<n1<<" "<<sign<<" "<<n2<<endl;
				st.push(n1 + n2);
			}
			else if(sign == '-')
			{
				cout<<n1<<" "<<sign<<" "<<n2<<endl;
				st.push(n1 - n2);
			}
		}
	}
	
	// 最后栈顶为结果
	cout<<st.top()<<endl;
	 
	return 0;
}

在这里插入图片描述

发布了52 篇原创文章 · 获赞 4 · 访问量 3796

猜你喜欢

转载自blog.csdn.net/weixin_44176696/article/details/104089300