《算法笔记》6.7小节——C++标准模板库(STL)介绍->stack的常见用法详解
A 简单计算器
题目描述
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
样例输出
12178.21
代码提交
#include<iostream>
#include<cstdio>
#include<string>
#include<stack>
#include<queue>
#include<map>
using namespace std;
struct node{
double num; //操作数
char op; //操作符
bool flag; //true表示操作数,false表示操作符
};
string str;
stack<node> s;
queue<node> q;
map<char, int> op;
void Change() //中缀转后缀
{
double num;
node temp;
for(int i = 0; i < str.length(); )
{ //如果是数字
if(str[i] >= '0' && str[i] <= '9')
{
temp.flag = true;
temp.num = str[i++] - '0'; //新节点已就绪
//当该操作数为多位数时
while(i < str.length() && str[i] >= '0' && str[i] <= '9')
{
temp.num = temp.num * 10 + (str[i] - '0');
i++;
}
q.push(temp);
}
else
{ //如果是操作符
temp.flag = false;
while(!s.empty() && op[str[i]] <= op[s.top().op])
{
q.push(s.top());
s.pop();
}
temp.op = str[i];
s.push(temp);
i++;
}
}
while(!s.empty()) //把操作符栈中的所有操作符弹出
{ //并压入队列中
q.push(s.top());
s.pop();
}
}
double Cal() //计算后缀表达式
{
double temp1, temp2;
node cur, temp;
while(!q.empty())
{
cur = q.front();
q.pop();
if(cur.flag == true) //是操作数则压入栈中
{
s.push(cur);
}
else
{
temp2 = s.top().num;
s.pop();
temp1 = s.top().num;
s.pop();
temp.flag = true;
if(cur.op == '+')
{
temp.num = temp1 + temp2;
}
else if(cur.op == '-')
{
temp.num = temp1 - temp2;
}
else if(cur.op == '*')
{
temp.num = temp1 * temp2;
}
else if(cur.op == '/')
{
temp.num = temp1 / temp2;
}
s.push(temp);
}
}
return s.top().num;
}
int main()
{
op['+'] = op['-'] = 1;
op['*'] = op['/'] = 2;
while(getline(cin, str), str != "0")
{
for(string::iterator it = str.end(); it != str.begin(); it--)
{
if(*it == ' ')
str.erase(it);
}
while(!s.empty())
{
s.pop();
}
Change();
printf("%.2f\n", Cal());
}
return 0;
}
笔记
这道题有一定的难度
1.需要掌握中缀表达式到后缀表达式的算法
https://blog.csdn.net/qq_44631615/article/details/115792028?
这个文有详细的演示过程可以参考
B Problem E
题目描述
请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。
输入
有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。
输出
对每个表达式,若其中的括号是匹配的,则输出”yes”,否则输出”no”。
样例输入
4
[(d+f)*{}]
[(2+3))
()}
[4(6]7)9
样例输出
yes
no
no
no
#include <cstdio>
#include <stack>
#include <string>
#include <iostream>
using namespace std;
stack<char> s;
bool judge(string str){
for(int i=0;i<str.length() ;i++){
if(str[i]=='('||str[i]=='['||str[i]=='{') s.push(str[i]) ;
if(str[i]==')'||str[i]==']'||str[i]=='}'){
if(str[i]==')'){
if(!s.empty() && s.top()=='('){
s.pop() ;
}
else return false;
}
else if(str[i]==']'){
if(!s.empty() &&s.top()=='['){
s.pop() ;
}
else return false;
}
else if(str[i]=='}'){
if(!s.empty() &&s.top()=='{'){
s.pop() ;
}
else return false;
}
}
}
if(s.empty()) return true;
return false;
}
int main(){
int m;
scanf("%d",&m);
getchar();
while(m--){
string str;
getline(cin,str);
while(!s.empty() ) s.pop() ;
if(judge(str)==true) printf("yes\n");
else printf("no\n");
}
return 0;
}