PIPIOJ-1292-中缀表达式转后缀表达式II

题目描述
PIPI现在有若干个包含小写英文字母作为操作数 以及 ‘+’, ‘-’, '’, ‘/’, ‘^’ ,’(’,’)‘七种操作符的合法中缀表达式。请你将其转为后缀表达式(逆波兰式)。
PS:’'代表幂运算,23=8
输入
输入一个字符串s,表示中缀表达式。
输出
输出一个字符串表示对应的后缀表达式。
样例输入
a+b
c+(de+f)g
样例输出
abc
+de
f+g*+

// 题目:中缀表达式转后缀表达式 II
// 日期:2021/7/14 
// 详情:有若干个包含小写英文字母作为操作数以及'+','-','*','/','^','(',')'五种操作符的合法中缀表达式。
//		 请你将其转为后缀表达式(逆波兰式)。
// XWQ
#include <bits/stdc++.h>
using namespace std;
void Check(string str){
	stack<char> op;
	int priority[300];
	priority['('] = 0; 	// 1.定义优先级
	priority['+'] = priority['-'] = 1; 
	priority['*'] = priority['/'] = 2;
	priority['^'] = 3;
	for(int i=0; i<str.size(); i++){
		if(str[i]>='a' && str[i]<='z'){
			printf("%c", str[i]);
		}
		else{
			if(op.empty()){
				op.push(str[i]);
			}
			else if(str[i]=='('){
				op.push(str[i]);
			}
			else if(str[i]==')'){	// 2*.比1291多了)步骤 
				while(!op.empty() && op.top()!='('){
					printf("%c", op.top());
					op.pop();
				}
				op.pop();	// 弹出左括号 
			}
			else{
				while(!op.empty() && priority[str[i]]<=priority[op.top()]){	// 2.使用优先级比较 
					printf("%c", op.top());
					op.pop();
				}
				op.push(str[i]);
			}
		}
	}	
	while(!op.empty()){
		printf("%c", op.top());
		op.pop();
	}
}
int main(){
	string str;
	cin >> str;
	Check(str);
}
中缀表达式转后缀表达式(也称为逆波兰表示法,Reverse Polish Notation,RPN),可以通过数据结构来完成。以下是简单的C语言代码实现: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义运算符优先级 #define PRECEDENCE(op) ((op)=='+' || (op)=='-' ? 1 : ((op)=='*' || (op)=='/' ? 2 : 0)) void infixToRPN(char* input, char* output) { stack<int> s; int i = 0; while (input[i] != '\0') { if (isalnum(input[i])) { // 遇到数字,直接放入output output[strlen(output)] = input[i]; output[strlen(output) + 1] = '\0'; i++; } else if (input[i] == '(') { // 遇到左括号,入 s.push(i); } else if (input[i] == ')') { // 遇到右括号,直到左括号出 while (!s.empty() && input[s.top()] != '(') output[strlen(output)] = input[s.pop()]; s.pop(); // 出左括号 } else { // 遇到操作符 while (!s.empty() && precedence(input[i]) <= precedence(input[s.top()])) { output[strlen(output)] = input[s.pop()]; } s.push(i); } i++; } // 把剩余的操作符依次压入结果 while (!s.empty()) { output[strlen(output)] = input[s.pop()]; } } int main() { char input[] = "A+B*C-(D+E)"; char output[100]; infixToRPN(input, output); printf("Infix expression: %s\n", input); printf("Postfix expression: %s\n", output); return 0; } ``` 这段代码首先定义了一个,遍历输入的中缀表达式。遇到数字直接加入输出,遇到左括号就入,遇到右括号则将左括号与之对应的运算符全部出。最后,把剩余的操作符依次压入结果。 运行这段代码会得到从给定的中缀表达式转换成的后缀表达式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值