convert expression from infix to postfix | c++ | stack

1. Topic description

Problem Description

The infix expression is the mathematical expression we usually write. The suffix expression is also called the reverse Polish expression. When the compiler checks the syntax of the expressions in the program we write, it can often pass the reverse Polish expression conduct. The program we want to design and implement is to convert the arithmetic expression represented by infix into postfix representation, for example, convert the infix expression

(A to (B*C + D)*E) / (F + G )

Converted to a suffix and expressed as: ABC*D+E*--FG+/

Note: In order to simplify the programming implementation, it is assumed that the variable names are all single letters, and the operators are only +, -, *, /, ^ and parentheses (), and the input arithmetic expressions are assumed to be correct.

Requirements: Implemented using a stack data structure, the input infix expression ends with a # sign

enter

integerN. Indicates that there are N infix expressions below and
N expressions consisting of single letters and operators

output

N postfix expressions.

test input expected output time limit memory limit extra process
Test case 1 display as text
  1. 1↵
  2. (A-(B*C+D)*E)/(F+G)#↵
display as text
  1. ABC*D+E*-FG+/↵
1 second 64M 0
Test case 2 display as text
  1. 2↵
  2. a+b*c-d#↵
  3. a-b*(c+d)#↵
display as text
  1. abc*+d-↵
  2. abcd+*-↵
1 second 64M 0

2. Thinking analysis

It's just a variant of a topic that was taught in a class.

To do this question, you need to know:

①Know what infix expressions and postfix expressions are.

②The basic operation of the stack.

③Basically understand how to use the stack to calculate common four arithmetic operations.

      In terms of grammar, the library that calls stack can make your program more concise and beautiful; in addition, because the numerical results are not calculated in real time, but instead of using alphabetic formulas, which involve the operation of character arrays, if you use string Much more convenient.

The infix expression calculation process is as follows:

(The picture comes from the PPT in the teacher's class)

        As for the specific operation process of converting infix to suffix, it is actually similar to the operation process of ordinary infix expressions. In view of the fact that the author is too lazy to write and feels that he can't express clearly at all, I suggest that students who want to know more should look at other materials on the Internet. Of course, after understanding the above infix expression algorithm, it is not difficult to figure out the infix to suffix by yourself.


3. Code implementation

#include<bits/stdc++.h> //万能头文件
using namespace std;
//TypeDe用来判断字符的类型,1表示字母变量,0表示七种运算符
int TypeDe(char c) {
	if (c=='+' || c=='-' || c=='*' || c=='/' || c=='^' || c=='(' || c==')') return 0;
	else return 1;
}

//拼接
void Joint(string *v1, string v2, char opn) {
	(*v1) = (*v1)+v2+opn;
	return;
}

//运算符等级优先度的量化评价
int lvl(char c) {
	switch (c) {
		case '(': return 0;            //“(”的优先级最低,这样其他运算符就可以直接进栈
		case '+': case '-': return 1;
		case '*': case '/': return 2;
		case '^': return 3;
		case ')': return 4;
	}
}

//运算符之间的优先级比较
int cmp(char ctop, char cnew) {
	int lvl(char);
	if (ctop=='^' && cnew=='^') return 0; //特殊情况,文末会说
	if ( lvl(ctop)>=lvl(cnew) ) return 1;
	else return 0;
}

//主程序
int main(){
	int n;
	cin >> n;
	int TypeDe(char);
	void Joint(string*, string, char);
	int lvl(char);
	
	for (int k=0;k<n;k++) {
		char c;
		stack<char> op;    //op是存放运算符的栈
		stack<string> vrle;//vrle是存放变量或者运算结果的栈
		while ( (c=getchar())!='#' ) {

			if (TypeDe(c)==1) { 
                //如果是字母变量,直接进栈vrle即可,注意这里会经过一个char->string的过程
				string cstr;
				cstr = c;
				vrle.push(cstr);
			}

			else if (op.size() && c!='(') {
				char op_top;
				op_top = op.top();
				while ( ((op_top!='(' && c==')') || cmp(op_top,c)>0) && op.size() ) {

					//如果外面的运算符优先级低于op顶部的运算符,就进行一次运算,并且弹栈一次
					string s2 = vrle.top();
					vrle.pop();
					Joint(&vrle.top(), s2, op_top);
					op.pop(); 
					if (op.size()) op_top = op.top();
					
				}
				if (c!=')') {
					op.push(c);
				}
				if (op.top()=='(') op.pop();
					
			}

			else {
                //如果栈空或者是左括号,直接进栈
				op.push(c);
			}

		}

        //op栈内可能还有未参与运算的运算符
		while (op.size()) {
			char op_top;
			op_top = op.top();
			string s2 = vrle.top();
			vrle.pop();
			Joint(&vrle.top(), s2, op_top);
			op.pop(); 
		}
		
        //输出
		while (vrle.size()) {
		    cout << vrle.top();
			vrle.pop();
		}
	}
	
	return 0;
}

 

an easy place to go wrong

A+B+C should be AB+C+

A^B^C should be ABC^^

Guess you like

Origin blog.csdn.net/m0_70241024/article/details/126974132