C++ infix expression to suffix expression method

  • 2020-08-22 22:37:17
  • OfStack

Example of this article for you to share C++ infix expression into suffix expression specific code, for your reference, the specific content is as follows

1. Initialize two stacks: operator stack s1 and intermediate result stack s2;

2. Scan infix expression from left to right;

3. When operands are encountered, press s2;

4. When an operator is encountered, compare its priority with the s1 top stack operator:

1), if s1 is empty, or the top of the stack operator is the left parenthesis "(", then push this operator onto the stack directly;
2), otherwise, if the priority is higher than the top of the stack operator, the operator is also pressed into s1
3). Otherwise, the top operator of s1 will pop up and press into s2, and then go to (4-1) to compare with the new top operator in s1;

5. When parentheses are used:

1) If the left bracket is "(", press s1 directly;
2). If the close bracket is ") ", the operator on the top of the s1 stack pops up in turn, and presses s2 until it encounters the open bracket. At this time, the 1 pair of parentheses is discarded;

6. Repeat steps 2 through 5 until you reach the rightmost point of the expression.

7. Pop the remaining operators in s1 and press into s2 in turn;

8. Pop the elements in s2 in turn and output, and the reverse order of the result is the suffix expression corresponding to the infix expression

Code:


#include<iostream>
#include<cstring>
#include<algorithm> 
#include<stack>
using namespace std;
 
stack<char> s1; // Operator stack  
stack<char> s2; // Intermediate result stack  
 
int f(const char str){
 int yxj; // priority  
 switch(str){
 case '*':yxj=5;break;
 case '/':yxj=5;break;
 case '+':yxj=4;break;
 case '-':yxj=4;break;
 }
 return yxj;
 
}
int main(){
 char c[100]="(12+4-13)+6*2";
 //char c[100]="1+((2+3)*4)-5";
 int lenc=strlen(c);
 // Read string  
 for(int i=0;i<lenc;i++){
 if(c[i]>='0'&&c[i]<='9'){ // If it's a number, just press in s2 
 s2.push(c[i]);
 }else if(c[i]=='+'||c[i]=='-'||c[i]=='*'||c[i]=='/'){ // If it's an operator  
 while(true){
 if(s1.empty()||s1.top()=='('){ //s1 Is empty   Or the top of the stack is ( 
 s1.push(c[i]);
 break;
 }else if(f(c[i])>f(s1.top())){ // The current operator priority is greater than s1 Stack top operator priority  
 s1.push(c[i]);
 break;
 }
 else{ // Less than or equal to  
 char cc=s1.top();
 s1.pop();
 s2.push(cc);
 }
 }
 }else{
 if(c[i]=='('){ // Directly read in  
 s1.push(c[i]);
 }else{
 while(s1.top()!='('){
 char ccc=s1.top();
 s1.pop();
 s2.push(ccc);
 }
 s1.pop();
 }
 }
 }
 while(!s1.empty()){
 char cccc=s1.top();
 s2.push(cccc);
 s1.pop();
 }
 
 //while(!s2.empty()){ // The result is in reverse order  
 // cout<<s2.top();
 // s2.pop();
 //}
 while(!s2.empty()){
 char c=s2.top();
 s1.push(c);
 s2.pop();
 }
 while(!s1.empty()){ 
 cout<<s1.top();
 s1.pop();
 }
 
 return 0;
}

Related articles: