栈的应用— 中缀表达式到后缀表达式的转换
代码:
# ifndef _INFIX_H_
# define _INFIX_H_
# include "stack.h"
# define MAX 50
typedef struct infix_Tag {
char target[MAX] ; //存放目标表达式
char * s ; //指向源表达式
char * t ; //指向当前扫描到得字符
}infix;
//////////////////////////////////////////////////////////////////////////
//操作
void initInfix(infix * fix) ; //初始化
void setExpr(infix * fix,char * str) ;//初始化源表达式
int priority(char ch) ; //返回运算符的权值(’*‘,’%‘,’/’ 为2 ,‘+’,‘-’为1)
void convent(infix * fix,stack *s) ; //将infix转换为postfix
void show(infix *fix) ; //显示表达式
# endif
实现
# include <ctype.h>
# include <stdio.h>
# include <string.h>
# include "infix.h"
# include "stack.h"
//初始化
void initInfix(infix * fix) {
strcpy(fix->target,"") ;
fix->t = fix->target ;
fix->s = "" ;
}
//初始化源表达式
void setExpr(infix * fix,char * str) {
fix->s = str ;
}
//返回运算符的权值(’*‘,’%‘,’/’ 为2 ,‘+’,‘-’为1)
int priority(char ch) {
if(ch == '*' || ch == '/' || ch == '%')
return 2 ;
else if (ch == '+' || ch == '-') {
return 1 ;
}
else
return 0 ;
}
//将infix转换为postfix
void convent(infix * fix,stack * s) {
while( *(fix->s) ) { //扫描表达式
if( *(fix->s) == 32) { //跳过空的字符
fix->s ++ ;
continue ;
} // end
if (isdigit( *(fix->s) ) || isalpha( *(fix->s) )) //扫描到数字和字母直接加入到postfix
{
while (isdigit( *(fix->s) ) || isalpha( *(fix->s) ) )
{
*(fix->t) = *(fix->s) ;
fix->t ++ ;
fix->s ++ ;
}
} // end if(char)
if( *(fix->s) == '*' || *(fix->s) == '/' || *(fix->s) == '%' ||
*(fix->s) == '+' || *(fix->s) == '-') { //扫描到运算符
char opr ;
if(!empty(s)) {
opr = getTop(s) ; //取出当前的栈顶元素
//将栈中所有权值大于扫描到运算符的权值的,都弹出
while( priority(opr) >= priority( *(fix->s) ) ) {
*(fix->t) = opr ;
fix->t ++ ;
pop(&s) ;
opr = getTop(s) ;
}
push(&s,*(fix->s)) ; //将当前扫描到元素入栈
}// end if(stack)
else
push(&s,*(fix->s)) ;//栈为空,直接将当前扫描到元素入栈
}//end if(operation)
if( *(fix->s) == '(' )
push(&s,*(fix->s)) ;
if( *(fix->s) == ')') {
char opr ;
if(!empty(s)) {
opr = pop(&s) ;
while(opr != '('){
*(fix->t) = opr ;
fix->t ++ ;
opr = pop(&s) ;
}
pop(&s) ;
}
}
fix->s ++ ;
} //end While
while(!empty(s)) { //将所有栈中元素添加到postfix中
char opr = pop(&s) ;
*(fix->t) = opr ;
fix->t ++ ;
}
*(fix->t) = '\0' ; //给postfix表达式,设置一个结束符号
}
void show(infix *fix) {
printf("%s\n",fix->target) ;
}
测试代码:
# include <stdio.h>
# include "infix.h"
int main()
{
infix fix ;
stack *s = NULL ;
initInfix(&fix) ;
char * str = "a+(b-c)*d+e-f" ;
setExpr(&fix,str) ;
convent(&fix,s) ;
show(&fix) ;
getchar();
return 0 ;
}
运行结果:
中缀式: char * str = "a+(b-c)*d+e-f" ;

浙公网安备 33010602011771号