OJ_计算不带括号的表达式

题干

OJ_计算不带括号的表达式_第1张图片

C++实现

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include 
using namespace std;

int main() {
	char str[1000] = { 0 };
	map<char, int> priority = {
		{'\0',0},
		{'+',1},
		{'-',1},
		{'*',2},
		{'/',2}
	};
	while (scanf("%s", str) != EOF) {
		string numStr = "";
		stack<char> opStack;
		stack<double> numStack;

		for (int i = 0; ; i++)
		{
			if (str[i] >= '0' && str[i] <= '9') {
				numStr.push_back(str[i]);
			}
			else {
				double num = stod(numStr);
				numStr = "";
				numStack.push(num);

				//什么时候弹栈:符号栈非空&&新运算符优先级不超过栈顶优先级
				while (!opStack.empty() && priority[str[i]] <= priority[opStack.top()]) {
					double num1 = numStack.top();
					numStack.pop();
					double num2 = numStack.top();
					numStack.pop();
					char curOp = opStack.top();
					opStack.pop();

					if (curOp == '+') {
						numStack.push(num2 + num1);
					}
					else if (curOp == '-') {
						numStack.push(num2 - num1);
					}
					else if (curOp == '*') {
						numStack.push(num2 * num1);
					}
					else if (curOp == '/') {
						numStack.push(num2 / num1);
					}
				}

				//此时符号栈为空,或新运算符优先级高于栈顶
				if (str[i] == '\0') {
					printf("%d\n",(int)numStack.top());
					break;
				}
				else {
					opStack.push(str[i]);
				}
			}
		}
	}

	return 0;
}

你可能感兴趣的:(数据结构与算法,算法,c语言,数据结构)