码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-11-09 01:04:29      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:数据结构

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

例如输入 (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;
}

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

标签:数据结构

原文地址:http://blog.csdn.net/hyczms/article/details/40934367

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!