数据结构与算法题目集7-21——求前缀表达式的值

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/84779939

我的数据结构与算法题目集代码仓:https://github.com/617076674/Data-structure-and-algorithm-topic-set

原题链接:https://pintia.cn/problem-sets/15/problems/836

题目描述:

知识点:前缀表达式的计算

思路:利用栈计算前缀表达式的值

前缀表达式的计算规则:

从右往左遍历表达式的每个数字和符号,遇到是数字就进栈, 遇到是符号,就将处于栈顶两个数字出栈,进行运算,运算结果进栈,一直到最终获得结果。

注意:本题所给的数字可能自带符号,即可能出现"-1"、"+2"这样的数字,还可能出现小数点

C++代码:

#include<iostream>
#include<stack>
#include<cstring>

using namespace std;

int main() {
	char input[31];
	scanf("%[^\n]", input);
	stack<double> Stack;
	for(int i = strlen(input) - 1; i >= 0; i--) {
		char c = input[i];
		if((c >= '0' && c <= '9') || (c == '.')) {
			char temp[31];
			int j = i, index = 0;
			while(j >= 0 && ((input[j] >= '0' && input[j] <= '9') || input[j] == '.')) {
				temp[index++] = input[j];
				j--;
			}
			temp[index] = '\0';
			char rev[31];
			for(int k = 0; k < strlen(temp); k++) {
				rev[k] = temp[index - k - 1];
			}
			rev[index] = '\0';
			double num;
			sscanf(rev, "%lf", &num);
			if(input[j] == '-') {
				num = -num;
				i = j;
			} else if(input[j] == '+') {
				i = j;
			}else{
				i = j + 1;
			}
			Stack.push(num);
		} else if(c != ' ') {
			double num1 = Stack.top();
			Stack.pop();
			double num2 = Stack.top();
			Stack.pop();
			if(c == '+') {
				Stack.push(num1 + num2);
			} else if(c == '-') {
				Stack.push(num1 - num2);
			} else if(c == '*') {
				Stack.push(num1 * num2);
			} else if(c == '/') {
				if(num2 == 0){
					printf("ERROR\n");
					return 0;
				}
				Stack.push(num1 / num2);
			}
		}
	}
	if(Stack.empty()) {
		printf("ERROR\n");
		return 0;
	}
	printf("%.1f\n", Stack.top());
	return 0;
}

C++解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/84779939