当前位置:网站首页>Infix expression is converted to suffix expression (C language code + detailed explanation)
Infix expression is converted to suffix expression (C language code + detailed explanation)
2022-07-02 19:38:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
Infix expression to suffix expression ( Ideas )
1. Create a stack 2. Get infix expressions from left to right
a. Digital direct output b. Operator Situation 1 : Left parenthesis encountered Direct stack , encounter Right bracket In the stack Left parenthesis After that, all operators on the stack pop up and output , meanwhile The left bracket comes out of the stack but does not output .
Situation two : Encounter multiplication sign and division sign Direct stack , Until you encounter an operator with a lower priority , Play the stack in turn .
Situation three : Plus and minus signs encountered , If at this time The stack is empty , be Direct stack , otherwise , In the stack High priority The operators of pop-up stack in turn ( Be careful : The plus and minus signs belong to the same priority , So play the stack in turn ) until Stack empty or encounter left parenthesis until , Stop playing stack .( Because the left bracket will pop up only when it matches the right bracket ).
Situation four : After obtaining , Pop up the remaining operation symbols in the stack and output
example : For example, will :2*(9+6/3-5)+4 Convert to suffix expression 2 9 6 3 / +5 – * 4 +
The conversion algorithm code is as follows :
/* Infix to suffix function */
void Change(SqStack *S,Elemtype str[])
{
int i=0;
Elemtype e;
InitStack(S);
while(str[i]!='\0')
{
while(isdigit(str[i]))
{/* Filter numeric characters , Direct output , Until the next non numeric character print space jumps out of the loop */
printf("%c",str[i++]);
if(!isdigit(str[i]))
{
printf(" ");
}
}
/* Addition and subtraction operators have the lowest priority , If the element at the top of the stack is empty, it will be directly put on the stack , Otherwise, it will be stored in the stack
All operators of play stack , If you encounter an open parenthesis, stop , Press the pop-up left bracket from the new stack , Because left
The parentheses pop up when they want to match the parentheses again , This will be discussed separately later . After popping up, press the operator with low priority into the stack */
if(str[i]=='+'||str[i]=='-')
{
if(!StackLength(S))
{
PushStack(S,str[i]);
}
else
{
do
{
PopStack(S,&e);
if(e=='(')
{
PushStack(S,e);
}
else
{
printf("%c ",e);
}
}while( StackLength(S) && e != '(' );
PushStack(S,str[i]);
}
}
/* When you encounter the right parenthesis , Pop up the remaining operators in brackets , Until the left bracket is matched
The left bracket only pops up and does not print ( The right bracket does not press the stack )*/
else if(str[i]==')')
{
PopStack(S,&e);
while(e!='(')
{
printf("%c ",e);
PopStack(S,&e);
}
}
/* ride 、 except 、 The left parentheses are high priority , Press the stack directly */
else if(str[i]=='*'||str[i]=='/'||str[i]=='(')
{
PushStack(S,str[i]);
}
else if(str[i]=='\0')
{
break;
}
else
{
printf("\n Input format error !\n");
return ;
}
i++;
}
/* Finally, flip the remaining operators in the stack in turn and print */
while(StackLength(S))
{
PopStack(S,&e);
printf("%c ",e);
}
}
The complete code is as follows :
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<assert.h>
#define INITSIZE 20
#define INCREMENT 10
#define MAXBUFFER 20
#define LEN sizeof(Elemtype)
/* Dynamic allocation storage structure of stack */
typedef char Elemtype;
typedef struct{
Elemtype *base;
Elemtype *top;
int StackSize;
}SqStack;
/* Initialization stack */
void InitStack(SqStack *S)
{
S->base=(Elemtype*)malloc(LEN*INITSIZE);
assert(S->base !=NULL);
S->top=S->base;
S->StackSize=INITSIZE;
}
/* Stack pressing operation */
void PushStack(SqStack *S,Elemtype c)
{
if(S->top - S->base >= S->StackSize)
{
S->base=(Elemtype*)realloc(S->base,LEN*(S->StackSize+INCREMENT));
assert(S->base !=NULL);
S->top =S->base+S->StackSize;
S->StackSize+=INCREMENT;
}
*S->top++ = c;
}
/* Ask for stack length */
int StackLength(SqStack *S)
{
return (S->top - S->base);
}
/* Pop stack operation */
int PopStack(SqStack *S,Elemtype *c)
{
if(!StackLength(S))
{
return 0;
}
*c=*--S->top;
return 1;
}
/* Infix to suffix function */
void Change(SqStack *S,Elemtype str[])
{
int i=0;
Elemtype e;
InitStack(S);
while(str[i]!='\0')
{
while(isdigit(str[i]))
{/* Filter numeric characters , Direct output , Until the next non numeric character print space jumps out of the loop */
printf("%c",str[i++]);
if(!isdigit(str[i]))
{
printf(" ");
}
}
/* Addition and subtraction operators have the lowest priority , If the element at the top of the stack is empty, it will be directly put on the stack , Otherwise, it will be stored in the stack
All operators of play stack , If you encounter an open parenthesis, stop , Press the pop-up left bracket from the new stack , Because left
The parentheses pop up when they want to match the parentheses again , This will be discussed separately later . After popping up, press the operator with low priority into the stack */
if(str[i]=='+'||str[i]=='-')
{
if(!StackLength(S))
{
PushStack(S,str[i]);
}
else
{
do
{
PopStack(S,&e);
if(e=='(')
{
PushStack(S,e);
}
else
{
printf("%c ",e);
}
}while( StackLength(S) && e != '(' );
PushStack(S,str[i]);
}
}
/* When you encounter the right parenthesis , Pop up the remaining operators in brackets , Until the left bracket is matched
The left bracket only pops up and does not print ( The right bracket does not press the stack )*/
else if(str[i]==')')
{
PopStack(S,&e);
while(e!='(')
{
printf("%c ",e);
PopStack(S,&e);
}
}
/* ride 、 except 、 The left parentheses are high priority , Press the stack directly */
else if(str[i]=='*'||str[i]=='/'||str[i]=='(')
{
PushStack(S,str[i]);
}
else if(str[i]=='\0')
{
break;
}
else
{
printf("\n Input format error !\n");
return ;
}
i++;
}
/* Finally, flip the remaining operators in the stack in turn and print */
while(StackLength(S))
{
PopStack(S,&e);
printf("%c ",e);
}
}
int main()
{
Elemtype str[MAXBUFFER];
SqStack S;
gets(str);
Change(&S,str);
return 0;
}
The operation effect screenshot is as follows :
How to calculate the value after converting infix expression into suffix expression
(https://blog.csdn.net/qq_42552533/article/details/86562791)
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/148663.html Link to the original text :https://javaforall.cn
边栏推荐
- 【ERP软件】ERP体系二次开发有哪些危险?
- Gmapping code analysis [easy to understand]
- Juypter notebook modify the default open folder and default browser
- zabbix5客户端安装和配置
- AcWing 1131. 拯救大兵瑞恩 题解(最短路)
- 中缀表达式转换为后缀表达式(C语言代码+详解)
- Getting started with typescript
- 安装单机redis详细教程
- AcWing 1137. Select the best line solution (the shortest circuit)
- VBScript详解(一)
猜你喜欢
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
搭建哨兵模式reids、redis从节点脱离哨兵集群
KS004 基于SSH通讯录系统设计与实现
Registration opportunity of autowiredannotationbeanpostprocessor in XML development mode
According to the atlas of data security products and services issued by the China Academy of information technology, meichuang technology has achieved full coverage of four major sectors
《架构整洁之道》读书笔记(下)
冒泡排序数组
字典
数据湖(十二):Spark3.1.2与Iceberg0.12.1整合
Thread application instance
随机推荐
《重构:改善既有代码的设计》读书笔记(下)
MySQL table historical data cleaning summary
golang:[]byte转string
mysql备份后缀是什么_mysql备份还原
IDEA编辑器去掉sql语句背景颜色SQL语句警告No data sources are configured to run this SQL...和SQL Dialect is Not Config
Advanced performance test series "24. Execute SQL script through JDBC"
Istio1.12:安装和快速入门
Quanzhi A33 uses mainline u-boot
Windows2008R2 安装 PHP7.4.30 必须 LocalSystem 启动应用程序池 不然500错误 FastCGI 进程意外退出
多端小程序开发有什么好处?覆盖百度小程序抖音小程序微信小程序开发,抢占多平台流量红利
使用xml文件打印mybaties-log插件的方式
AcWing 1135. 新年好 题解(最短路+搜索)
PHP parser badminton reservation applet development requires online system
Codeworks round 802 (Div. 2) pure supplementary questions
ShardingSphere-JDBC5.1.2版本关于SELECT LAST_INSERT_ID()本人发现还是存在路由问题
Data dimensionality reduction factor analysis
In pytorch function__ call__ And forward functions
AcWing 903. 昂贵的聘礼 题解(最短路—建图、dijkstra)
第七章-类基础
Preprocessing and preprocessing macros