数据结构-怀化学院期末题(58)

今天发现了一个事情,学校平台可以交c++代码,那以后都用c++。但是不可以使用迭代器,否则会出现编译错误!!!

题目描述:

小学求算式问题。要求采用栈实现。

输入:

输入第一行为用例个数n。

接下来n个表达式。

输出:

对每一个用例的表达式,输出其结果。

输入样例:

3

2+5

4+2*3-10/5

3*7-2

输出样例:

7

8

19

代码:

cpp 复制代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
typedef pair<int,int> PII;
const int N = 1e5 + 10;
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 temp.num = temp1 / temp2;
			s.push(temp);
		}
	}
	return s.top().num;
}
int main(){
	op['+'] = op['-'] = 1;
	op['/'] = op['*'] = 2;
	int rrrr;
	cin >> rrrr;
	getchar();
	int num = 0;
	while(getline(cin,str),str != "0"){
		while(!s.empty()) s.pop();//初始化栈
		Change();  //中缀表达式转后缀表达式
		printf("%.d\n",int(Cal()));  //计算后缀表达式
		num ++;
		if(num == rrrr) return 0;
	}
	return 0;
}
相关推荐
zhong liu bin1 小时前
MySQL数据库面试题整理
数据结构·数据库·mysql
Aczone281 小时前
硬件(六)arm指令
开发语言·汇编·arm开发·嵌入式硬件·算法
逐雨~2 小时前
9.8C++作业
开发语言·c++
luckys.one5 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|7 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师7 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo37 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC8 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
利刃大大9 小时前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
C语言小火车9 小时前
【C++八股文】基础知识篇
c++·tcp/ip·const·智能指针·多线程同步·static关键字·c++内存模型