数据结构:栈的典型应用之二:四则运算表达式求值(C++)

#include <iostream>
#include <stack>
using namespace std;
/************************************************************************/
/* 表达式求值                                                                     */
/************************************************************************/
#define MaxSize 100
void trans(char exp[], char postexp[])
{
	stack<char> op;
	int i = 0, j = 0;
	//op.top = -1;
	while (*exp != '\0')
	{
		switch (*exp)
		{
		case '('://左括号进栈
			op.push(*exp);
			exp++;
			break;
		case ')'://将栈中“(”以前的运算符依次删除存入数组exp中,然后将“(”删除
			while (!op.empty() && op.top() != '(')
			{
				postexp[i++] = op.top();
				op.pop();
			}
			op.pop();
			exp++;
			break;
		case '+':
		case '-':
			while (!op.empty() && op.top() != '(')
			{//将栈中优先级大于等于‘+’或'-'的运算符退栈并存放到postexp中
				postexp[i++] = op.top();
				op.pop();
			}
			op.push(*exp);
			exp++;
			break;
		case '*':
		case '/':
			while (!op.empty() && (op.top() == '*' || op.top() == '/'))
			{//将栈中的“*”或者是“/”运算符依次出栈并存放到postexp中
				postexp[i++] = op.top();
				op.pop();
			}
			op.push(*exp);
			exp++;
			break;
		case ' ':break;
		default:
			while (isdigit(*exp))
			{
				postexp[i++] = *exp;
				exp++;
			}
			postexp[i++] = '#';
		}
	}
	while (!op.empty())//最后的扫描工作
	{
		postexp[i++] = op.top();;
		op.pop();;
	}
	postexp[i] = '\0';
	cout << "后缀表达式" << endl;
	for (j = 0; j < i; j++)
	{
		if(postexp[j]=='#')
			j++;
		cout << postexp[j];
	}
	cout << endl;
}

float compvalue(char postexp[])
{
	stack<float> st;
	float a, b, c, d;
	
	while(*postexp != '\0')
	{
		switch(*postexp)
		{
		case '+':
			a = st.top();
			st.pop();
			b = st.top();;
			st.pop();;
			c = a + b;
			st.push(c);
			break;	

		case '-':
			a = st.top();
			st.pop();
			b = st.top();;
			st.pop();;
			c = b -a;
			st.push(c);
			break;

		case '*':
			a = st.top();
			st.pop();
			b = st.top();;
			st.pop();;
			c = a*b;
			st.push(c);
			break;	

		case '/':
			a = st.top();
			st.pop();
			b = st.top();;
			st.pop();;
			if (a != 0)
			{
				c = b / a;
				st.push(c);
			}
			else
			{
				cout << "除零错误!" << endl;
				exit(0);
			}
			break;
		default://进行最后的扫尾工作,将数字字符转换成数值存放到d中
			d = 0;
			while (isdigit(*postexp))
			{
				d = 10 * d + *postexp - '0';
				postexp++;
			}
			st.push(d);
			break;

		}
		postexp++;
	}
	return (st.top());
}

int main()
{
	char exp[MaxSize]="((18+6)*2-9)/2";
	char postexp[MaxSize]={0};
	trans(exp, postexp);//exp存放中缀表达式,postexp存放后缀表达式
	printf( "后缀表达式的值\n");
	printf("%.2f\n", compvalue(postexp));
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值