数据结构之简单四则运算表达式求值8-(栈的实现)

利用栈实现简单的四则运算,有待提升的地方有,不支持负数的运算,只支持0-9之间数值的计算

代码如下

#include <iostream>
#include <stack>
#include <string>

using namespace std;

void InfixToPostfix(string &str1, string &str2, stack<char> &s)
{
	char ch, temp;
	for (size_t i = 0; i != str1.size(); ++i)
	{
		ch = str1[i];		//获取当前字符 
		if (ch >= '0' && ch <= '9')
			str2.push_back(ch);		//放入str2中
		if (ch == '(')
			s.push(ch);			//入栈
		if (ch == ')')		//右括号 
		{
			do{
				temp = s.top();		//获取当前栈顶元素
				if (temp != '(')
				{
					str2.push_back(temp);
					s.pop();		//出栈 
				}
				else
				{
					s.pop();
					break;
				}
			} while (!s.empty());
		}
		if (ch == '*' || ch == '/')		//处理乘号及除号 
		{
			if (s.empty())		//栈中无符号 
			{
				s.push(ch);
				continue;
			}
			temp = s.top();
			if (temp == '+' || temp == '-' || temp == '(')
				s.push(ch);		//入栈
			if (temp == '*' || temp == '/')
			{
				str2.push_back(temp);
				s.pop();
				s.push(ch);
			}
		}
		if (ch == '+' || ch == '-')
		{
			if (s.empty())		//栈中无符号 
			{
				s.push(ch);
				continue;
			}
			temp = s.top();
			if (temp == '(')
				s.push(ch);
			if (temp == '+' || temp == '-')
			{
				str2.push_back(temp);
				s.pop();
				s.push(ch);
			}
			if (temp == '*' || temp == '/')
			{
				str2.push_back(temp);
				s.pop();
				if (s.empty())
					s.push(ch);			//第一种情况直接放
				//特殊情况处理 
				else
				{
					temp = s.top();		//获取下一个符号
					if (temp == '-' || temp == '+')
					{
						str2.push_back(temp);
						s.pop();
					}
					s.push(ch);
				}
				
			}
		}
	}
	//处理栈中剩余部分 
	while (!s.empty())
	{
		temp = s.top();
		str2.push_back(temp);
		s.pop();
	}	
} 

//后缀表达式求值 
int GetResult(string &str2) 
{
	stack<int> is;
	
	int t1, t2, t3;
	char ch;
	
	//扫描整个后缀表达式 
	for (size_t i = 0; i != str2.size(); ++i)
	{
		ch = str2[i];
		if (ch >= '0' && ch <= '9')
			is.push(ch - '0');		//减去字符0转换成int类型 
		else
		{
			switch(ch)
			{
				case '+':
			 	t1 = is.top();
			 	is.pop();
			 	t2 = is.top();
			 	is.pop();
			 	t3 = t2 + t1;
			 	is.push(t3);
			 	break;
			case '-':
			 	t1 = is.top();
			 	is.pop();
			 	t2 = is.top();
			 	is.pop();
			 	t3 = t2 - t1;
			 	is.push(t3);
			 	break;
			case '*':
			 	t1 = is.top();
			 	is.pop();
			 	t2 = is.top();
			 	is.pop();
			 	t3 = t2 * t1;
			 	is.push(t3);
			 	break;
			case '/':
			 	t1 = is.top();
			 	is.pop();
			 	t2 = is.top();
			 	is.pop();
			 	t3 = t2 / t1;
			 	is.push(t3);
			 	break;
			}
		}
	}
	return is.top(); 
}

int main()
{
	string str1, str2;
	stack<char> s;			//作为栈
	cout << "请输入正确的表达式:";
	cin >> str1;
	InfixToPostfix(str1, str2, s);
	cout << "转换的后缀表达式为:" << str2 << endl;
	cout << "最终的值为:" << GetResult(str2) << endl;
	 
	return 0;
}
运行结果如下


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值