数据结构-怀化学院期末题(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;
}
相关推荐
少许极端5 小时前
算法奇妙屋(二十八)-递归、回溯与剪枝的综合问题 1
java·算法·深度优先·剪枝·回溯·递归
仰泳的熊猫5 小时前
题目1453:蓝桥杯历届试题-翻硬币
数据结构·c++·算法·蓝桥杯
rainbow68895 小时前
C++STL list容器模拟实现详解
开发语言·c++·list
唐梓航-求职中5 小时前
技术-算法-leetcode-1606. 找到处理最多请求的服务器(易懂版)
服务器·算法·leetcode
啊阿狸不会拉杆5 小时前
《机器学习导论》第 10 章-线性判别式
人工智能·python·算法·机器学习·numpy·lda·线性判别式
会叫的恐龙5 小时前
C++ 核心知识点汇总(第11日)(排序算法)
c++·算法·排序算法
twilight_4695 小时前
机器学习与模式识别——线性回归算法
算法·机器学习·线性回归
玄同7656 小时前
Python Random 模块深度解析:从基础 API 到 AI / 大模型工程化实践
人工智能·笔记·python·学习·算法·语言模型·llm
爱吃生蚝的于勒6 小时前
【Linux】线程概念(一)
java·linux·运维·服务器·开发语言·数据结构·vim
Pluchon6 小时前
硅基计划4.0 算法 简单模拟实现位图&布隆过滤器
java·大数据·开发语言·数据结构·算法·哈希算法