表达树形式

/*表达树形式*/
#include<iostream>
#include<cstring>
using namespace std;

const int MAX=1000;
int lchild[MAX],rchild[MAX];
char ope[MAX];
int data[MAX];
int count=0;

bool isPureData(const string& str,int from,int to,int& data){
	data=0;
	for(int i=from;i<to&&str[i]<='9'&&str[i]>='0';++i){
		data*=10;
		data+=str[i]-'0';
	}
	return i==to;
}

int build_tree(const string& str,int from,int to){
	int p=0,f1=-1,f2=-1;
	int da;
	if(isPureData(str,from,to,da)){
		int n=count++;
		lchild[n]=-1,rchild[n]=-1;
		data[n]=da;
		return n;
	}
	int t=from;
	while(t<to){
		switch(str[t]){
		case '(':
			--p;
			break;
		case ')':
			++p;
			break;
		case '+':
		case '-':
			if(!p)f1=t;
			break;
		case '*':
		case '/':
			if(!p)f2=t;
			break;
		}
		++t;
	}
	if(f1<0)f1=f2;
	if(f1<0) return build_tree(str,from+1,to-1);//( )
	int lch=build_tree(str,from,f1);
	int rch=build_tree(str,f1+1,to);
	int n=count++;
	lchild[n]=lch;
	rchild[n]=rch;
	ope[n]=str[f1];
	return n;
}

int val(int pos){
	if(lchild[pos]==-1) return data[pos];
	int a=val(lchild[pos]);
	int b=val(rchild[pos]);
	switch(ope[pos]){
	case '+':
		return a+b;
		break;
	case '-':
		return a-b;
		break;
	case '*':
		return a*b;
		break;
	case '/':
		if(b==0)return -1;
		return a/b;
		break;
	}
}


int calculator(const string& str,int l){
	count=0;
	build_tree(str,0,l);
	return val(count-1);
}

int main(){
	string str="(12-(2/(2/2)+2*4))/2-10";
	cout<<calculator(str,str.length())<<endl;
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值