首页 > 代码库 > 建算数表达式树并计算(应付作业,仅供参考)

建算数表达式树并计算(应付作业,仅供参考)

只是为了应付数据结构老师布置的作业,算式里的数只能是整数:

例如输入 (6+3)*(4-2)*(41-1)

输出 720.00

#include <stdio.h>
#include <string.h>
const int N = 1000;
int m[N], flag;
double res;
struct Node {
	double val;
	char c;
	Node* left;
	Node* right;
	Node() {
		left = right = NULL;
		c = 'a' - 1;
	}
};

Node* build(char *str, int l, int r) {
	int flag1 = -1, flag2 = -1, p = 0;
	Node* node = new Node;
	if (r - l == 1) {
		node -> val = m[str[l]];
		return node;
	}
	for (int i = l; i < r; i++) {
		switch(str[i]) {
			case '(' : p++; break;
			case ')' : p--; break;
			case '+' :
			case '-' :
				if (!p)
					flag1 = i;
				break;
			case '*' :
			case '/' :
				if (!p)
					flag2 = i;
				break;
		}
	}
	if (flag1 < 0)
		flag1 = flag2;
	if (flag1 < 0)
		return build(str, l + 1, r - 1);
	node -> left = build(str, l, flag1);
	node -> right = build(str, flag1 + 1, r);
	node -> c = str[flag1];
	return node;
}

double preOrder(Node* root) {
	if (root == NULL)
		return 0;
	if (root -> c == 'a' - 1)
		return root -> val;	
	double a;
	switch(root -> c) {
		case '+': a = preOrder(root -> left) + preOrder(root -> right);
		break;
		case '-': a = preOrder(root -> left) - preOrder(root -> right);
		break;
		case '*': a = preOrder(root -> left) * preOrder(root -> right);
		break;
		case '/': 
			if (preOrder(root -> right) != 0)
				a = preOrder(root -> left) / preOrder(root -> right);
			else
				flag = 1;
		break;
	}
	return a;
}

int main() {
	Node* root;	
	char str[N], s[N];
	while (scanf("%s", str) != EOF) {
		memset(m, 0, sizeof(m));
		res = flag = 0;
		int len = strlen(str);
		int n = 0;
		char a = 'a';
		if (str[0] == '-')
			s[n++] = a++;
		for (int i = 0; i < len; i++) {
			if (str[i] > '9' || str[i] < '0')
				s[n++] = str[i];
			else {
				int sum = 0;
				while (str[i] >= '0' && str[i] <= '9') {
					sum = sum * 10 + str[i] - '0';
					i++;
				}
				i--;
				m[a] = sum;
				s[n++] = a++;
			}
		}
		s[n] = '\0';
		root = build(s, 0, n);
		res = preOrder(root);
		if (!flag)
			printf("表达式结果: %.2lf\n", res);
		else
			printf("error!\n");
	}
	return 0;
}

建算数表达式树并计算(应付作业,仅供参考)