数据结构实验之栈与队列二:一般算术表达式转换成后缀式
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Example Input
a*b+(c-d/e)*f#
Example Output
ab*cde/-f*+
如果是字母的话直接输出,遇见运算符和栈顶的运算符比较优先级,若优先级高于栈顶则入栈,否则输出并出栈,遇到左括号时 入栈,遇到右括号时将运算符输出并出栈至左括号。
#include <stdio.h> #include <stdlib.h> typedef char elemtype; typedef int status; #define MAXSIZE 100 #define OVERFLOW -2 #define another 50 #define true 1 #define false 0 typedef struct { elemtype *base; elemtype *top; int stacksize; }Sqstack; status isEmpty(Sqstack &S){ if(S.top == S.base) return true; else return false; } void initStack(Sqstack &S){ S.base = new elemtype[MAXSIZE]; S.top = S.base; S.stacksize = MAXSIZE; } elemtype getTop(Sqstack &S){ if(S.base == S.top) return false; else return *(S.top-1); } void Push(Sqstack &S, elemtype e){ //压栈 if(S.top-S.base >= S.stacksize){ S.base = (elemtype *)realloc(S.base,(another+S.stacksize)*sizeof(elemtype)); S.top = S.base + S.stacksize; S.stacksize += another ; } *S.top++ = e; } elemtype Pop(Sqstack &S, elemtype &e){ if(S.top == S.base) return false; return e = * --S.top; } int precede(char ch){ //一开始挨个比较的,比较乱,这种方式比较简洁 int flag; if(ch == '+'|| ch == '-') flag = 1; else if(ch == '*'|| ch == '/') flag = 2; else if(ch == '(') flag = 3; else if(ch == ')') flag = 4; return flag; } void getPostfix(Sqstack &S, char str[]){ char ch; for(int i = 0; str[i] != '#'; i++){ if(str[i]>='a' && str[i]<='z'){ printf("%c", str[i]); } else { if(isEmpty(S)){ Push(S, str[i]); } else if(precede(str[i]) > precede(getTop(S))){ if(str[i] == ')'){ while(getTop(S) != '('){ printf("%c", getTop(S)); Pop(S, ch); } Pop(S, ch); } else Push(S, str[i]); } else { if(getTop(S) != '('){ printf("%c", getTop(S)); Pop(S, ch); Push(S, str[i]); } else { Push(S, str[i]); } } } } while(!isEmpty(S)){ char c; Pop(S, c ); printf("%c", c); } } int main(){ Sqstack S; initStack(S); char str[55]; scanf("%s", str); getPostfix(S, str); printf("\n"); return 0; }