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;