后缀表达式(stack)

1、题目

所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。

如:3*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。’@’为表达式的结束符号。‘.’为操作数的结束符号。

输入格式: 

3.5.2.-*7.+@

输出格式: 

输出:表达式的值

16

1、1基于二叉树的后序遍历理解后缀表达式 

(挖个坑 ,以后填)

2、题解

#include <iostream>
#include<string>
#include<stack>
#include<sstream> //istringstream要用到的头文件
using namespace std;
int main()
{
	string str;
	cin >> str;
	stack<int>s;
	int temp=0;
	int i = 0;
	while (str[i] != '@') {
		if (str[i] == '+') {
			temp = s.top();
			s.pop();
			temp += s.top();
			s.pop();
			s.push(temp);
		}
		else if (str[i] == '-') {	
			temp = s.top();
			s.pop();
			temp = s.top() - temp;
			s.pop();
			s.push(temp);
		}
		else if (str[i] == '*') {	
			temp = s.top();
			s.pop();
			temp *= s.top();
			s.pop();
			s.push(temp);
		}
		else if (str[i] == '/') {
			
			temp = s.top();
			s.pop();
			temp = s.top() / temp;
			s.pop();
			s.push(temp);
		}
		else {
			int pos = str.find('.', i);
			istringstream zxc(str.substr(i, pos-i));//zxc为类型名		
			zxc >> temp;
			s.push(temp);
			i = pos;
		}
		i++;
	}
	cout << temp;
}

3、stack的基础操作

stack.pop();//出栈,数据类型void
stack.push(a);//压栈
stack.top();//返回栈顶的数据

4、字符串转换为其他数据(多种方式)

1、利用头文件

利用#include<sstream>里的istringstream数据类型

如下部分代码:

istringstream zxc(str.substr(i, pos-i));//zxc为类型名		
			zxc >> temp;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值