[Note Detailed Illustration] How to convert infix expressions into postfix expressions? data structure

infix expression

Infix expression (infix notation) is a general expression method of arithmetic or logical formulas. The operator is in the middle of the operand in infix form(for example: 3 + 4). Infix expression is a commonly used arithmetic expression. display method.

Unlike prefix or suffix notation, brackets are required in infix notation. During calculation, operators and corresponding operands must be enclosed in parentheses to indicate the order of operations.

postfix expression

Reverse Polish notation (RPN, or reverse Polish notation) is a mathematical expression method introduced by Polish mathematician Jan Vukasiewicz in 1920. In reverse Polish notation , all operators Placed after the operand, it is also called postfix notation . Reverse Polish notation does not require parentheses to indicate operator precedence.

Convert infix expression to postfix expression

Ideas for converting infix to suffix

  1. Initialize two stacks: operator stack S1 ; operand stack S2
  2. Scan infix expressions from left to right
  3. When an operand is encountered, push it onto the operand stack S2
  4. When an operator is encountered, compare its priority with the operator on the top of operator stack S1.
  5. If the operator stack S1 is empty, or the operator on the top of the stack is a left bracket " ( ", or the priority is higher than the priority of the operator on the top of the stack, this operator is directly pushed onto the stack.
  6. Otherwise, the operator on the top of operator stack S1 is popped and pushed into operand stack S2 , and the priority comparison with the operator on the top of operator stack S1 is performed again.
  7. When a parenthesis is encountered, if the left parenthesis " ( " is encountered, it is directly pushed into the operator stack S1 ;
  8. If the right bracket " ) " is encountered, the operators on the top of the operator stack S1 are popped out in turn, and pushed into the operand stack S2 until the left bracket " ( " is encountered, at which time the pair of brackets is discarded
  9. Repeat steps 2 to 8 until the rightmost part of the expression
  10. Pop the remaining operators from operator stack S1 and push them into operand stack S2.
  11. Splice the elements in the operand stack S2 and output them. The result is the postfix expression corresponding to the infix expression.

Infix to suffix icon

The figure below is the complete process using 9-2*3+(5-2)*2 as an example.

Infix to suffix flow chart

Infix to suffix code analysis

main function

First initialize the string that needs to be converted into suffix notation, and then give an array to store the suffix expression. Assume that the function for converting infix to suffix is ​​MidtoLast. Pass the character array of infix expression to this function, midstr, and Character array laststr that stores the suffix expression:

int main()
{
	char midstr[] = "9-2*3+(5-2)*2";//中缀表达式
	printf("中缀表达式为:%s\n", midstr);
	char laststr[100];//后缀表达式
	MidtoLast(laststr, midstr);
	printf("后缀表达式为:%s\n", laststr);

	return 0;
}

operand encountered

Traverse the entire infix string array and store it directly when encountering numeric characters. Here we use the isdigit function to determine whether it is a numeric character. In the relevant summary section below, we will explain how to use the function in detail. Here you only need to know first Its header file is #include <ctype.h> ;

for (int i = 0; midstr[i] != '\0';)//i有的情况是不++的
{
	if (isdigit(midstr[i]))//数字字符直接放到后缀表达式里
    {
        laststr[j++] = midstr[i++];
    }
}

operator encountered

When encountering an operator: When encountering the first operator, it is pushed directly onto the stack. According to the priority, it is judged who pops the stack first and who pops last. The priority of "*" and "/" is higher than that of "+" ""-" priority:

brackets encountered

And when you encounter an operator (not ")") that you want to push onto the stack, and the top of the stack is "(", just push it directly onto the stack:

for (int i = 0; midstr[i] != '\0';)//i有的情况是不++的
{
	else if (  top == 0 ||
			   midstr[i] == '(' ||
			   (midstr[i] == '*' || midstr[i] == '/') && (mystack[top - 1] == '+' || mystack[top - 1] == '-') || 
               mystack[top - 1] == '(' && midstr[i] != ')')
			   
    {
         mystack[top++] = midstr[i++];
    }	  
}

pop

 When ")" is encountered and the top element of the stack is "(", it will be offset directly:

for (int i = 0; midstr[i] != '\0';)//i有的情况是不++的
{
	else if (midstr[i] == ')' && mystack[top - 1] == '(')//直接抵消
		{
			i++;
			top--;
		}
}

All remaining operators are popped off the stack

Pop all remaining elements from the stack one after another:

else//直接出栈
{
    laststr[j++] = mystack[--top];
}

while (top > 0)
{
	laststr[j++] = mystack[--top];
}

laststr[j] = '\0';//变为字符串

Complete code for converting infix to suffix

#include <stdio.h>
#include <ctype.h>

void MidtoLast(char* laststr, const char* midstr)
{
	int j = 0;//后缀表达式
	char mystack[100];//模拟栈
	int top = 0;//栈顶指针,当前可以存放数据的下标

	for (int i = 0; midstr[i] != '\0';)//i有的情况是不++的
	{
		if (isdigit(midstr[i]))//数字字符直接放到后缀表达式里
			laststr[j++] = midstr[i++];
		else if (top == 0 ||
			midstr[i] == '(' ||
			(midstr[i] == '*' || midstr[i] == '/') && (mystack[top - 1] == '+' || mystack[top - 1] == '-') ||
			mystack[top - 1] == '(' && midstr[i] != ')')
			mystack[top++] = midstr[i++];
		else if (midstr[i] == ')' && mystack[top - 1] == '(')//直接抵消
		{
			i++;
			top--;
		}
		else//直接出栈
			laststr[j++] = mystack[--top];
	}

	while (top > 0)
	{
		laststr[j++] = mystack[--top];
	}
	laststr[j] = '\0';//变为字符串
}

int main()
{
	char midstr[] = "9-2*3+(5-2)*2";//中缀表达式
	printf("中缀表达式为:%s\n", midstr);
	char laststr[100];//后缀表达式
	MidtoLast(laststr, midstr);
	printf("后缀表达式为:%s\n", laststr);

	return 0;
}

Related knowledge points

isdigit function:

Example:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
    char str[] = "1776ad";
    int year;
    if (isdigit(str[0]))
    {
        year = atoi(str);
        printf("The year that followed %d was %d.\n", year, year + 1);
    }
    return 0;
}

operation result: 

 

Guess you like

Origin blog.csdn.net/2301_78131481/article/details/134079076