信息学奥赛一本通1331【例1-2】后缀表达式的值 (栈)

 

1331:【例1-2】后缀表达式的值


时间限制: 10 ms         内存限制: 65536 KB
提交数: 22710     通过数: 4230

【题目描述】

读入一个后缀表达式(字符串),只含有0-9组成的运算数及加(+)、减(—)、乘(*)、除(/)四种运算符。每个运算数之间用一个空格隔开,不需要判断给你的表达式是否合法。以@作为结束标志。

比如,16–9*(4+3)转换成后缀表达式为:16□9□4□3□+*–,在字符数组A中的形式为:

栈中的变化情况:

运行结果:-47

提示:输入字符串长度小于250,参与运算的整数及结果之绝对值均在264264范围内,如有除法保证能整除。

【输入】

一个后缀表达式。

【输出】

一个后缀表达式的值。

【输入样例】

16 9 4 3 +*-@

【输出样例】

-47

提交 统计信息 提交记录


教学备忘录:编辑
给学生提示:编辑

遇到数字就保存到num数组中(可能是多位数,需进行处理),注意数据范围,num数组需用longlong,否则过不了。

遇到字符就让最后保存的两个数进行运算,注意减法和除法的运算顺序,倒数第二个保存的数减去(除以)最后保存的那个数,运算后将结果保存在倒数第二个保存的数的位置(此时这个数更新为最后保存的数的位置,其数组下标前一个位置则为此时的倒数第二个保存的数),以此类推,这是用数组模拟栈的方法。

中缀转后缀、计算后缀表达式

#include <iostream>
#include <string>
#include <stack>
#include <cstring> 
using namespace std;

long long num[1005];

int main()
{
	string str;
	getline(cin, str);
	int len = str.length();
	int cnt = 0;
	for (int i = 0; i < len - 1; i ++) { // i<len-1为了不包含最后的@
		if (str[i] == '+') { // 对四则运算进行处理 注意减法和除法的 被减数 和 被除数 的位置
			num[cnt-2] += num[cnt-1];
			cnt --;
		}
		else if (str[i] == '-') {
			num[cnt-2] -= num[cnt-1];
			cnt --;
		}
		else if (str[i] == '*') {
			num[cnt-2] *= num[cnt-1];
			cnt --;
		}
		else if (str[i] == '/') {
			num[cnt-2] /= num[cnt-1];
			cnt --;
		}
		else {
			long long x = 0;
			while (str[i] != ' ') {
				x = x*10 + str[i]-'0';
				i ++;
			}
			num[cnt++] = x;//printf("%lld\n", x); //测试num中保存的数值
		}
	}
	cout << num[0] << endl;
	return 0;
}

补充一个用stack的

#include <iostream>
#include <string>
#include <cstdio>
#include <stack>
#include <cstring> 
using namespace std;

stack <long long> s;

int main()
{
	string str;
	getline(cin, str);
	int len = str.length();
	long long x;
	for (int i = 0; i < len - 1; i ++) { 
		x = 0;
		long long a, b;
		if (str[i] == '+') { 
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();
			s.push(a+b);
		}
		else if (str[i] == '-') {
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();
			s.push(b-a);
		}
		else if (str[i] == '*') {
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();
			s.push(a*b);
		}
		else if (str[i] == '/') {
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();
			s.push(b/a);
		}
		while (str[i] >= '0' && str[i] <= '9') {
			x = x*10 + str[i]-'0';
			if (str[i+1] == ' ') {
				s.push(x);
				x = 0;
			}
			i ++;
		}
	}
	printf("%lld\n", s.top());
	return 0;
}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值