栈的应用——中缀表达式转后缀表达式

中缀转后缀过程:

1. 对于数字:直接输出

2. 对于符号:

    2.1 左括号:进栈 

    2.2 运算符号:(与栈顶符号进行优先级比较,若栈顶符号优先级低:此符号进栈;若栈顶符号优先级不低:将栈顶符号弹出并输出,之后进栈)

                若是乘除直接进栈;

                若是加减,与栈顶比较,若栈顶是乘除,直接输出,否则进栈。

    2.3 右括号:将栈顶符号弹出并输出,直到匹配左括号

遍历结束:将栈中的所有符号弹出并输出

 

后缀表达式的求值:

如果是数字压入栈中;如果是操作符,则从栈中退出两个操作数,运算后压入栈中;最后栈顶存放的就是计算结果。

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int IsNumber(char a) {
	return a >= '0'&&a <= '9';
}

int IsLeft(char a) {
	return a == '(';
}

int IsRight(char a) {
	return a == ')';
}

int IsPlusorMimus(char a) {
	return a == '+' || a == '-';
}

int IsMultiorDivi(char a) {
	return a == '*' || a == '/';
}

int main()
{
	string str = "8+(3-1)*5";
	stack<char> s;
	int size = str.size();
	char temp;
	for (int i = 0; i < size; i++) {
		if (IsNumber(str[i])) {
			cout << str[i];
		}
		if (IsLeft(str[i])) {
			s.push(str[i]);
		}
		if (IsRight(str[i])) {
			while (s.size()>0) {
				temp = s.top();
				if (IsLeft(temp)) {
					s.pop();
					break;
				}
				else {
					cout << temp;
					s.pop();
				}
			}
		}
		if (IsPlusorMimus(str[i])) {
			if (s.size()==0)
				s.push(str[i]);
			else {
				temp = s.top();
				if (IsMultiorDivi(temp))
					cout << str[i];
				else
				{
					s.push(str[i]);
				}
			}
		}
		if (IsMultiorDivi(str[i])) {
			s.push(str[i]);
		}
	}
	while (s.size())
	{
		temp = s.top();
		cout << temp;
		s.pop();
	}
	cout << endl;
	system("pause");
	return 0;
}

 

中缀表达式转后缀表达式的过程可以通过来实现。具体步骤如下: 1. 初始化两个,一个用于存储运算符的OPTR,一个用于存储换后的后缀表达式OPND。 2. 从左到右扫描中缀表达式,如果遇到操作数,则直接压入OPND中;如果遇到运算符,则与OPTR顶元素进行比较,如果该运算符优先级高于OPTR顶元素,则将该运算符压入OPTR中;否则,将OPTR顶元素弹出并压入OPND中,直到该运算符优先级高于OPTR顶元素或OPTR为空,然后将该运算符压入OPTR中。 3. 如果遇到左括号,则直接压入OPTR中;如果遇到右括号,则将OPTR顶元素弹出并压入OPND中,直到遇到左括号,然后将左括号弹出。 4. 当扫描完整个中缀表达式后,将OPTR中剩余的运算符依次弹出并压入OPND中。 5. 最后,将OPND中的元素依次弹出,即可得到换后的后缀表达式。 下面是一个示例代码,供参考: ``` #include <iostream> #include <stack> #include <string> using namespace std; int priority(char op) { if (op == '+' || op == '-') { return 1; } else if (op == '*' || op == '/') { return 2; } else { return 0; } } string infixToPostfix(string infix) { stack<char> optr; string postfix = ""; for (int i = 0; i < infix.length(); i++) { char ch = infix[i]; if (isdigit(ch)) { postfix += ch; } else if (ch == '(') { optr.push(ch); } else if (ch == ')') { while (optr.top() != '(') { postfix += optr.top(); optr.pop(); } optr.pop(); } else { while (!optr.empty() && priority(ch) <= priority(optr.top())) { postfix += optr.top(); optr.pop(); } optr.push(ch); } } while (!optr.empty()) { postfix += optr.top(); optr.pop(); } return postfix; } int main() { string infix = "1+(2-3)*4+10/5"; string postfix = infixToPostfix(infix); cout << postfix << endl; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值