后缀表达式的值c++

后缀表达式的值

如果是0~9的个位数的话,遇到数字进栈,遇到符号弹出栈顶和次栈顶,运算后入栈

Eg:

1 2 3 + 6 – 2 9 * + *

从左到右遍历,a[0]是数字1,入栈,a[1]a[2],是数字,入栈

栈内:1,2,3

a[3]+是符号弹出栈顶和次栈顶,相加

栈内:1

2+3=5

入栈

栈内:1,5

6是数字,入栈

栈内:1,5,6

-是符号,弹出栈顶和次栈顶(减法除法时,次栈顶运算栈顶)

6-5=1

栈内:1,1

2,数字入栈9入栈

栈内:1,1,2,9

*弹出栈顶和次栈顶:

2*9=18

栈内:1,1,18

1+18=19

栈内:1,19

1+19=20

栈内:20

结果:20

栈:

1

1 2

1 2 3

1 5

1 5 6

1 1

1 1 2

1 1 2 9

1 1 18

1 19

20

代码:

#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack <long long> s;
int main()
{
	string a;
	long long t=-1,m,n,ans,i=0;//2^64
	getline(cin,a);
	while (a[i]!=64)
	{
		if (a[i]>=48&& a[i]<=57) 
		{
			if (t==-1)
			{
				t=a[i]-48;
				s.push(t);
			}
			else
			{
				t = s.top();
				s.pop();
				t = t * 10 + (a[i] - '0');
				s.push(t);
			}
		}
		if (a[i]==32) t = -1;
		if (a[i]==43) 
		{
			m=s.top();
			s.pop();
			n=s.top();
			s.pop();
			ans = m + n;
			s.push(ans);//压入运算结果 

		}
		if (a[i]==45)//是减号 
		{
			m = s.top(); 
			s.pop(); 
			n = s.top(); 
			s.pop();
			ans = n-m;
			s.push(ans);
			//同上
		}
		if (a[i]==42)//是乘号 
		{
			m = s.top(); 
			s.pop(); 
			n = s.top(); 
			s.pop();
			ans = n*m;
			s.push(ans);
			//同上 
		}
		if (a[i]==47)//是除号 
		{
			m = s.top(); 
			s.pop(); 
			n = s.top(); 
			s.pop();
			ans = n/m;//次栈顶/栈顶 
			s.push(ans);
			//同上 
		}
		i++;
	}
	cout<<s.top();//栈里最后一个 
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值